2013-01-15 86 views
1

我不是英語非常好,我主要是用Java開發,我試圖創建一個clickevent外部evenlistener,但我不斷收到的感覺,這是錯誤的。這在C#中被認爲是不好的做法嗎?

這是我的例子: 形式..

public partial class MainFrame : System.Windows.Forms.Form 
{ 
    private System.ComponentModel.Container components = null; 
    private System.Windows.Forms.Button startButton; 

    public MainFrame() 
    { 
     initGUI(); 
    } 

    private void initGUI() 
    { 
     this.components = new System.ComponentModel.Container(); 

     this.Text = "CustomGUI"; 

     ShowIcon = false; 

     this.startButton = new System.Windows.Forms.Button(); 
     startButton.Text = "Start"; 
     startButton.SetBounds(0, 0, 100, 25); 

     this.Controls.Add(this.startButton); 

     MainEventListener listen = new MainEventListener(); 
     startButton.Click += listen.startClicked; 

    } 


} 

下一頁:聽衆..

class MainEventListener 
{ 

    public void startClicked(object sender, System.EventArgs e) 
    { 
     Application.Exit(); 
    } 


} 

最後:主要方法..

class ApplicationStarter 
{ 

    static void Main(string[] args) 
    { 
     MainFrame frame = new MainFrame(); 
     System.Windows.Forms.Application.Run(frame); 
    } 
} 

我一直感覺我做錯了。

回答

2
  1. 你不必自己寫這一切。 Visual Studio提供了一個模板和一個Designer來管理所有的表單初始化和配置代碼。 (InitGUI =>在部分類中的InitializeComponent)。

  2. 在C#中,你不必創建一個監聽器類。只需使用事件。

+0

這不添加無用的代碼一樣的NetBeans? – user1705828

+0

我不知道的NetBeans,但不妨一試。那裏的脂肪不多。 –

+0

它增加了很多額外的代碼,但它隱藏在設計文件中。它隱藏了組件定位和事件接線。你只需要說「onClick」在visual studio中的事件設置中做「xyz」。然後,它會在代碼中創建你的事件處理程序,如果你想 – devshorts

相關問題