如何处理鼠标事件

1 c#

我想点击一个正方形,然后一个"X"应该出现里面,但我不知道在里面放什么Form1_MouseDown,Form1_PaintForm1_MouseUp事件.我怎样才能实现这个C#?

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 VTest
{
    public partial class Form1 : Form
    {
        Rectangle rect; // single rect
        int sqsize, n;
        int margin;

        public Form1()
        {
            n = 3;
            margin = 25;
            sqsize = 50;
            rect = new Rectangle(10, 10, 150, 150);
            InitializeComponent();
        }

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            // what goes here?
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            // what goes here?
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            // what goes here?
        }

        // ...
Run Code Online (Sandbox Code Playgroud)

Mus*_*sis 6

在MouseDown事件中,确定是否在矩形内发生了单击很容易:

if (rect.Contains(e.Location))
{
    // the user has clicked inside your rectangle
}
Run Code Online (Sandbox Code Playgroud)

在表单上绘制"X"也很容易:

Graphics g = this.CreateGraphics();
g.DrawString("X", this.Font, SystemBrushes.WindowText,
    (float)e.X, (float)e.Y);
Run Code Online (Sandbox Code Playgroud)

但是,在这种情况下,"X"将不会持久,这意味着如果您在表单上拖动另一个表单然后将其移走,则"X"将不再存在.要绘制持久性"X",请创建一个表单级Point变量,如下所示:

private Point? _Xlocation = null;
Run Code Online (Sandbox Code Playgroud)

如果用户单击Rectangle,请使用MouseDown事件设置此变量:

if (rect.Contains(e.Location))
{
    _Xlocation = e.Location;
    this.Invalidate(); // this will fire the Paint event
}
Run Code Online (Sandbox Code Playgroud)

然后,在表单的Paint事件中,绘制"X":

if (_Xlocation != null)
{
    e.Graphics.DrawString("X", this.Font, SystemBrushes.WindowText,
        (float)e.X, (float)e.Y);
}
else
{
    e.Graphics.Clear(this.BackColor);
}
Run Code Online (Sandbox Code Playgroud)

如果您希望当用户放开鼠标按钮时"X"消失,只需将此代码放入MouseUp事件:

_Xlocation = null;
this.Invalidate();
Run Code Online (Sandbox Code Playgroud)

您可以根据自己的喜好将其变得更加复杂.使用此代码,"X"将在您单击表单的任何位置的下方和右侧绘制.如果希望"X"以点击位置为中心,可以使用Graphics对象的MeasureString方法确定"X"的高度和宽度,并相应地偏移DrawString位置.