net: [[C#]]

使用框架

实现鼠标点击显示提示

代码实现:

1
2
3
4
5
6
7
8
private void Form1_MouseClick(object sender, MouseEventArgs e) { //鼠标事件
if (e.Button == MouseButtons.Left) {
MessageBox.Show("你单击了鼠标左键!", "提示");
}
if (e.Button == MouseButtons.Right) {
MessageBox.Show("你单击了鼠标右键!", "提示");
}
}

如果运行后无论怎么点击都没有反应,那么有可能是没有在Form控件上绑定鼠标事件。你需要在Form的构造函数中添加以下代码:

1
this.MouseClick += new MouseEventHandler(Form1_MouseClick);

将这个代码放在InitializeComponent()的后面即可。这样就可以在鼠标单击事件发生时调用Form1_MouseClick方法,然后弹出提示消息。

实现显示鼠标坐标

使用label显示

你可以在 Form1_MouseMove 方法中更新 Label 或其他控件的文本,显示当前鼠标位置的信息。 以下是示例代码:

1
2
3
4
5
6
private void Form1_MouseMove(object sender, MouseEventArgs e) {
// 获取鼠标位置
int x = e.X; int y = e.Y;
// 将鼠标位置信息显示在 Label 上
label1.Text = "当前鼠标位置:X = " + x + ", Y = " + y;
}

在上面的代码中,我们首先获取了鼠标的 X 和 Y 坐标。然后将这些坐标信息拼接成一段文本,最后将这个文本显示在 Label 控件上。 你可以将上述代码复制到你的 Form1 类中,并将 Form1_MouseMove 事件处理程序与 MouseMove 事件绑定,以便在鼠标移动时显示位置信息。

然而为使用label显示鼠标位置信息,需要先创建一个label,方法如下:
可以在 Visual Studio 的窗体设计器中添加 Label 控件,具体方法如下:

  1. 打开窗体设计器。在解决方案资源管理器中双击要编辑的窗体(例如 Form1.cs)。
  2. 在工具箱中找到 “Label” 组件,如果你没有在工具箱中看到 “Label” 组件,可以在工具箱中右键单击选中的工具箱选项卡然后选择 “items” 来添加控件。
  3. 单击 “Label” 并将其拖到窗体设计区域中。
  4. 在窗体设计器中选择 Label 控件,然后打开属性窗口。
  5. 将 Label 控件的属性设置为想要显示的文本、字体等。 完成上述步骤后,你的标签就已经被添加到窗体上了,并且可以在代码中使用 label1 引用它。

如果你想在运行时动态创建 Label 控件,则可以使用下面的代码:

1
2
3
4
Label myLabel = new Label(); 
myLabel.Location = new Point(10, 10);
myLabel.Text = "这是一个新的 Label 控件";
this.Controls.Add(myLabel);

在上面的代码中,我们首先创建了一个新的 Label 控件。 然后,我们设置它的位置和文本,最后将它添加到窗体的控件集合中。现在,你就可以在代码中通过 myLabel 引用新的 Label 控件了。

使用paint事件显示

以上是使用label显示坐标的方法,但仍然可以采用paint事件显示鼠标的坐标:
 

1
2
3
4
5
6
7
8
9
10
11
12
 //使用前不要忘了绑定print事件
private int x = 0;
private int y = 0;
private const int DrawPositionX = 100;
private const int DrawPositionY = 100;
private void Form1_MouseMove(object sender, MouseEventArgs e) {
x = e.X; y = e.Y; this.Invalidate();
}
private void Form1_Paint(object sender, PaintEventArgs e) {
Font font = new Font("Arial", 20f);
e.Graphics.DrawString(x.ToString() + "," + y.ToString(), font, new SolidBrush(Color.Red), DrawPositionX, DrawPositionY);
}
 


References