c# - 如何从 KeyDown 方法中使用 PaintEventArgs 调用方法

标签 c# winforms

我正在学习表单应用程序,并且对它的整个工作方式非常陌生。我想在用户按键时在屏幕(行)上绘制一些内容,但我不知道如何将 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类时,不需要订阅KeyDownKeyUp等事件油漆。相反,您应该重写相应的方法 OnKeyDownOnKeyUpOnPaint。在您的情况下,您应该在重写的 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/

相关文章:

c# - 用于 Mono 的 Winforms 或 XWT GUI 设计器?

c# - 在多线程应用中卡住

c# - Maskedtextbox 掩码根据操作系统语言而变化

c# - 在用户控件中公开控件的 itemsource 属性

c# - 编写 Windows 窗体应用程序时 Application.StartupPath 和 AppDomain.CurrentDomain.BaseDirectory 之间的首选项

c# - 制作 ToolStripMenuItem.Selected = true 的最简单方法

c# - 为什么我不能将表单标签添加到我的标签列表中?

.net - Arial Unicode MS是WinForms UI的正确字体吗?

c# - 如何在同一集合位置替换列表中的值

c# - 从 bin 目录中删除 DLL 会导致 ASP.NET MVC 中出现编译错误