绘制一个窗体 窗体内“单击鼠标左键”,在鼠标处绘制一个“绿圆” 窗体内“单击鼠标右键”,在鼠标处绘制一个“红色方框” 窗体内“双击鼠标左键”,清空所有已画“圆”和“方”
时间: 2023-11-03 22:04:41 浏览: 31
以下是C#代码实现:
```
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
int mouseX, mouseY; // 鼠标位置
bool isLeftClicked, isRightClicked; // 是否按下鼠标左键、右键
bool isDoubleClick; // 是否双击鼠标左键
public Form1()
{
InitializeComponent();
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
mouseX = e.X;
mouseY = e.Y;
if (e.Button == MouseButtons.Left)
{
if (!isDoubleClick) // 如果不是双击,则绘制绿圆
{
Graphics g = this.CreateGraphics();
Brush brush = new SolidBrush(Color.Green);
g.FillEllipse(brush, mouseX - 10, mouseY - 10, 20, 20);
}
isDoubleClick = false; // 重置状态
}
else if (e.Button == MouseButtons.Right) // 绘制红色方框
{
Graphics g = this.CreateGraphics();
Pen pen = new Pen(Color.Red, 2);
g.DrawRectangle(pen, mouseX - 20, mouseY - 20, 40, 40);
}
}
private void Form1_MouseDoubleClick(object sender, MouseEventArgs e)
{
isDoubleClick = true;
this.Invalidate(); // 重绘窗体
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left) isLeftClicked = true;
else if (e.Button == MouseButtons.Right) isRightClicked = true;
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left) isLeftClicked = false;
else if (e.Button == MouseButtons.Right) isRightClicked = false;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (isDoubleClick) // 清空所有已画“圆”和“方”
{
Graphics g = e.Graphics;
g.Clear(Color.White);
}
}
}
}
```
在窗体设计器中,将MouseDoubleClick、MouseDown、MouseUp、MouseClick事件绑定到Form1中,并将Paint事件绑定到Form1中。
运行程序,单击鼠标左键绘制绿圆,单击鼠标右键绘制红色方框,双击鼠标左键清空窗体。