我正在學習表單應用程式,并且對它的整個作業方式非常陌生。我想在用戶按鍵時在螢屏(行)上繪制一些東西,但我不知道如何將 PaintEventArgs 決議為該方法。我讀過不同的帖子,但我不明白我實際上應該做什么。大多數say use都嘗試了一些東西,但不能從MethodPictureBox呼叫paint 。KeyDown
我KeyDown還在InitializeComponent.
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);
}
uj5u.com熱心網友回復:
從Form類繼承時,不需要訂閱KeyDown、KeyUp或等事件Paint。相反,您應該覆寫相應的方法OnKeyDown, OnKeyUp, OnPaint。在您的情況下,您應該在覆寫OnPaint方法中撰寫您的繪制邏輯,并直接在Graphics通過的物件上繪制PaintEventArgs.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();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/526557.html
標籤:C#表格
