2014-07-23 48 views
0

我需要幫助在WinForm上畫一條線。C#線條繪畫問題

的代碼我現在有大部分被拉斷的MSDN:

using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace BouncingBall 
{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     this.Invalidate(); 
    } 
    private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) 
    { 

     // Insert code to paint the form here. 
     Pen pen = new Pen(Color.FromArgb(255, 0, 0, 0)); 
     e.Graphics.DrawLine(pen, 10, 10, 300, 200); 
    } 
} 

}

目前,這個代碼不畫任何東西。

+3

This Works。你真的有一個事件處理程序將表單的Paint事件連接到你的方法嗎? – vcsjones

+0

並且由於@PaulG不存在,請務必在完成後丟棄該筆 – Justin

+1

嘗試重寫OnPaint方法而不是調用Form1_Paint事件。你顯然沒有把事件聯繫起來。 – LarsTech

回答

1

您發佈的代碼沒問題。它呈現在表格中間的黑線:

enter image description here

我懷疑你的問題是你沒有表單的Paint事件訂閱您Form1_Paint方法。你不能只是把這個方法放在那裏,並期望它被神奇地稱呼。

您可以修復,通過將它添加到您的窗體的構造函數:

public Form1() 
{ 
    InitializeComponent(); 
    this.Paint += Form1_Paint; 
} 

或者,也可以在設計,它做了同樣的事件訂閱做到這一點,它只是塔克斯它拿走的InitializeComponent()內。

+0

是的,就是這樣。我還想問另外一個問題:我應該使用Windows窗體來繪製一個包含幾個幾何形狀的簡單二維遊戲的圖形嗎?還是有另一種更有效的方法,我應該使用? – palmerito0

+0

@ palmerito0我不是遊戲的專家,所以我不能說真的。然而,依賴於GDI的WinForms並不是硬件加速的,所以如果你每秒重繪30次,你會看到高CPU使用率。我會看看使用DirectX的遊戲框架。 – vcsjones

+0

等待,但不是DirectX for C++? – palmerito0

0

根據MSDN:

using System.Drawing;

Pen myPen; 
myPen = new Pen(System.Drawing.Color.Red); 
Graphics formGraphics = this.CreateGraphics(); 
formGraphics.DrawLine(myPen, 0, 0, 200, 200); 
myPen.Dispose(); 
formGraphics.Dispose(); 

你的代碼實際上看起來不錯,你確定方法射擊?

+1

或更好的地方創建筆對象,使用()語句 – Justin