2012-07-29 50 views
2

我想調用panel1用橙色線(用藍線啓動)重新繪製面板的繪畫方法。C#Panel.Refresh()不調用paint方法

我已經試過無效(),更新()和刷新(),但似乎沒有任何調用PANEL1的Paint事件......

Paint事件處理程序已被添加到PANEL1:

this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint); 

有人可以協助嗎?

static class Program 
{ 
    /// <summary> 
    /// The main entry point for the application. 
    /// </summary> 
    [STAThread] 
    static void Main() 
    { 
     Application.EnableVisualStyles(); 
     Application.SetCompatibleTextRenderingDefault(false); 

     Form1 testForm = new Form1(); 
     Application.Run(testForm); 

     testForm.drawNewLine(); 
    } 
} 

public partial class Form1 : Form 
{ 
    bool blueLine = true; 
    bool orangeLine = false; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void panel1_Paint(object sender, PaintEventArgs e) 
    { 
     Graphics g = e.Graphics; 

     if (blueLine == true) 
     { 
      Pen bluePen = new Pen(Color.Blue, 3); 
      g.DrawLine(bluePen, 30, 50, 30, 250); 
     } 
     else if (orangeLine == true) 
     { 
      Pen orangePen = new Pen(Color.Orange, 3); 
      g.DrawLine(orangePen, 30, 50, 30, 250); 
     } 

     g.Dispose(); 
    } 

    public void drawNewLine() 
    { 
     blueLine = false; 
     orangeLine = true; 
     //panel1.Invalidate(); 
     //panel1.Update(); 
     panel1.Refresh(); 
    } 
} 

回答

7

Application.Run(testForm);塊,直到窗體關閉,所以當drawNewLine()被稱爲 - 形式不存在了(創建一個按鈕,要求其點擊次數和檢查自己的代碼工作)。 Invalidate()應該工作得很好。

另外,您不應該在處理paint事件時處理傳遞給您的代碼的Graphics對象。你不負責創建它,所以讓創建它的代碼去銷燬它。

此外,處置Pen對象,因爲你正在創建它們。

+0

太棒了!非常感謝! – williamwallace 2012-07-29 09:32:06