我正在学习表单应用程序,并且对它的整个工作方式非常陌生。我想在用户按键时在屏幕(行)上绘制一些内容,但我不知道如何将 PaintEventArgs 解析为该方法。我读过不同的帖子,但我不明白我实际上应该做什么。大多数人说使用 PictureBox
尝试了一些东西,但无法从 KeyDown
方法调用绘图。
我还在 InitializeComponent
中添加了我的 KeyDown
方法。
this.KeyDown += new KeyEventHandler(this.Form1_KeyDown);
提前致谢。
代码:
private void Form1_KeyDown(object sender, KeyEventArgs ke)
{
if (ke.KeyCode == Keys.Space)
{
Custom_Paint(sender, needPaintEventArgsHere);
}
}
private void Custom_Paint(object sender, PaintEventArgs pe)
{
Graphics g = pe.Graphics;
Pen blackPen = new Pen(Color.Black, 1);
pe.Graphics.DrawLine(blackPen, 200.0F, 400.0F, 500.0F, 700.0F);
}
最佳答案
继承Form
类时,不需要订阅KeyDown
、KeyUp
或等事件油漆
。相反,您应该重写相应的方法 OnKeyDown
、OnKeyUp
、OnPaint
。在您的情况下,您应该在重写的 OnPaint
方法中编写绘制逻辑,并直接在通过 PaintEventArgs.Graphics
传递的 Graphics
对象上绘制。之后,当您需要重绘时,只需调用 Control.Invalidate
即可触发 OnPaint
方法。
此外,您可能希望为您的 Form
启用双缓冲,如构造函数中所示。
public partial class Form1: Form
{
private bool m_isSpaceKeyPressed = false;
public Form1()
{
SetStyle(ControlStyle.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true);
InitializeComponent();
}
protected override void OnPaint(object sender, PaintEventArgs e)
{
base.OnPaint(e);
if(!m_isSpaceKeyPressed)
return;
Graphics g = e.Graphics;
Pen blackPen = new Pen(Color.Black, 1);
g.Graphics.DrawLine(blackPen, 200.0F, 400.0F, 500.0F, 700.0F);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
m_isSpaceKeyPressed = true;
Invalidate();
}
}
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
m_isSpaceKeyPressed = false;
Invalidate();
}
}
}
关于c# - 如何从 KeyDown 方法中使用 PaintEventArgs 调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74294735/