2014-01-07 125 views
-1

我的問題是如何繪製在C#中的子窗口的簡單線,即:在子窗口繪圖 - C#

  • 我有一個父窗口,一個按鈕。點擊按鈕,顯示一個子窗口,並在其上繪製一條線。

那麼,我該怎麼做?這是我的子窗口代碼:

public partial class Form2 : Form 
{ 
    Pen pen; 
    public Form2() 
    { 
     InitializeComponent(); 
     pen = new Pen(Color.Black); 
    } 


    private void Form2_Paint(object sender, PaintEventArgs e) 
    { 
     Graphics g; 
     g = this.CreateGraphics(); 
     e.Graphics.DrawLine(pen, 10, 10, 100, 100); 
    } 

} 

謝謝。

+0

它適合我。 –

+0

什麼不適合你?子窗口不顯示,行不顯示等 –

+0

@Adrian Faciu子窗口出現,但該線沒有繪製。 –

回答

4

下面的代碼是更好:

private void Form2_Paint(object sender, PaintEventArgs e) 
{ 
    Graphics g = e.Graphics; 
    using (Pen p = new Pen(Color.Black)) 
    { 
     g.DrawLine(pen, 10, 10, 100, 100); 
    } 
} 

使用圖形例如油漆事件,並使用語法自動處置筆對象

Remeber調用在這樣的父窗口顯示方法:

private void button_Click(object sender, EventArgs e) 
{ 
    Form form2 = new Form2(); 
    form2.ShowDialog(); 
} 
+0

對不起,但它沒有奏效。 –

+1

@EB你用手寫** Form2_Paint **方法嗎? GUI Designer不能在Designer文件中註冊事件。 – CzBiX

+0

沒有用手寫。我以通常的方式註冊了活動。 –