提问人:Foros 提问时间:11/16/2023 更新时间:11/20/2023 访问量:57
为什么我按 D 时矩形不动?
Why does the rectangle not move when i press D?
问:
所以我正在尝试为大学的一个项目制作一个类似油漆的程序,我必须让形状移动。我们的教授建议我们使用 KeyDown,但由于某种原因,我无法弄清楚为什么它不会移动。代码如下
public partial class Form1 : Form
{
Rectangle rect = new Rectangle();
bool isMouseDown = false;
public Form1()
{
InitializeComponent();
this.Width = 900;
this.Height = 700;
bm = new Bitmap(pic.Width, pic.Height);
bm2 = new Bitmap(pic2.Width, pic2.Height);
g = Graphics.FromImage(bm);
g2 = Graphics.FromImage(bm2);
g.Clear(Color.Transparent);
pic.Image = bm;
pic2.Image = bm2;
pic.Parent = pic2;
pic.BackColor = Color.Transparent;
pic2.BackColor = Color.Transparent;
}
Bitmap bm, bm2;
Graphics g, g2;
bool paint = false;
Point px, py;
private Point MouseDownLocation;
Pen p = new Pen(Color.Black, 1);
int index;
Pen erase = new Pen(Color.Transparent, 10);
int x, y, sX, sY, cX, cY;
ColorDialog cd = new ColorDialog();
Color new_color;
private void pic_MouseDown(object sender, MouseEventArgs e)
{
paint = true;
MouseDownLocation = e.Location;
py = e.Location;
px = e.Location;
cX = e.X;
cY = e.Y;
sX = e.X;
sY = e.Y;
}
private void pic_MouseMove(object sender, MouseEventArgs e)
{
if (paint)
{
if (index == 1)
{
px = e.Location;
g.DrawLine(p, px, py);
py = px;
}
if (index == 2)
{
px = e.Location;
g.DrawLine(erase, px, py);
py = px;
}
}
pic.Refresh();
x = e.X;
y = e.Y;
sX = e.X - cX;
sY = e.Y - cY;
}
private void pic_MouseUp(object sender, MouseEventArgs e)
{
isMouseDown = false;
paint = false;
sX = x - cX;
sY = y - cY;
if (index == 3)
{
g.DrawEllipse(p, cX, cY, sX, sY);
}
if (index == 4)
{
rect = new Rectangle(cX, cY, sX, sY);
g.DrawRectangle(p, rect);
}
if (index == 5)
{
g.DrawLine(p, cX, cY, x, y);
}
}
private void pic_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
if (paint)
{
if (index == 3)
{
g.DrawEllipse(p, cX, cY, sX, sY);
}
if (index == 4)
{
g.DrawRectangle(p, rect);
}
if (index == 5)
{
g.DrawLine(p, cX, cY, x, y);
}
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.D)
{
rect.X += 10;
}
}
我尝试使用Form1_KeyDown功能移动它,但我无法弄清楚或找到任何有帮助的在线资源。
答:
0赞
PrfctByDsgn
11/20/2023
#1
首先,我会在Form1_KeyDown中放置一个断点,以验证当您按下某个键时代码是否被执行。或者,您可以在那里放置一个 Debug.Writeline() 调用,并在键入时观察输出窗口。
看不到矩形移动的原因可能是在更改矩形后pic_Paint未调用。为此,您应该在更改位置后调用 Invalidate() 以调用表单的重绘。
评论
Form1_KeyDown