因此,我试图使一个项目在大学油漆一样的程序,我必须使形状移动。我们的教授建议,我们使用按键,但由于某种原因,我不能弄清楚为什么它不会移动。代码如下
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函数移动它,但我找不到它,也找不到任何有帮助的在线资源。
1条答案
按热度按时间91zkwejq1#
首先,我会在Form1_KeyDown中放置一个断点,以验证当你按下一个键时代码是否会被执行。或者,你可以在那里放置一个soft.Writeline()调用,并在键入时观察输出窗口。
你没有看到矩形移动的原因可能是在你改变矩形后没有调用pic_Paint。要实现这一点,你应该在改变位置后调用Invalidate()来调用窗体的重绘。