编程技术 · 2018 年 12 月 07 日 0

C#在picturebox上画一个矩形,并跟随鼠标拖动

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace T392419114
{
    public partial class Form1 : Form
    {
        private int x = 100;
        private int y = 100;
        private int w = 120;
        private int h = 80;

        public Form1()
        {
            InitializeComponent();
            pictureBox1.Refresh();
        }

        int dx = 0;
        int dy = 0;

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.X >= x && e.X <= x + w && e.Y >= y && e.Y <= y + h)
            {
                this.Cursor = Cursors.Hand;
                if (e.Button == System.Windows.Forms.MouseButtons.Left)
                {
                    x = e.X - dx;
                    y = e.Y - dy;
                    pictureBox1.Refresh();
                }
                else
                {
                    dx = e.X - x;
                    dy = e.Y - y;
                }

            }
            else
            {
                if (e.Button == System.Windows.Forms.MouseButtons.None) this.Cursor = Cursors.Default;
            }
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics sss = e.Graphics;
            Pen testpen = new Pen(Color.Red, 3);
            sss.DrawRectangle(testpen, x, y, w, h);
        }
    }
}

 

完整代码:https://download.csdn.net/download/caozhy/10557637