2012-05-19 46 views
1

我正在製作一個小型簡單的Windows應用程序。這是我的主要功能:刷新表單窗口

static void Main() 
{ 

    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false); 

    // This will be my Form object 
    Form1 robotPath = new Form1(); 

    Application.Run(robotPath); 

    // at this point I'll try to make changes to my object 
    // for instance I'll try to change a background image 
    robotPath.changeImage(); 
} 

然而,改變我的對象後,更改不會反映在輸出窗口(背景沒有改變)。我試過robotPath.refresh()和robotPath.invalidate(),但仍然沒有改變背景。但是,當我使用按鈕單擊事件調用changeImage函數時,它可以工作。但我希望在不使用按鈕/鼠標事件的情況下更改它(隨着Form1對象的更改,背景會發生變化) 任何建議?

回答

3
Application.Run() 

直到主窗體關閉才返回。在Application.Run()之後運行的所有代碼在程序關閉之前不會運行。這顯然不是你想要的。

您可以通過重新安排你的main解決這個問題很容易就夠了:

Form1 robotPath = new Form1(); 
robotPath.changeImage(); 
Application.Run(robotPath); 

另一種方法是將呼叫轉移到changeImage進入Form1構造函數,或將觸發早在窗體的生活中的一些事件,例如Load。該選項更好地封裝了表單的行爲。

+0

感謝大衛,我實際上通過在Application.Run()之前創建一個線程來解決問題,該線程在需要時調用changeImage(),並照顧我想要的東西! – sj47sj