2012-05-01 49 views
-1

我想學習C#GUI編程和我有一個關於默認代碼以下問題在C#文本框:文本框的GUI編程

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

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

     private void textBox1_TextChanged(object sender, EventArgs e) 
     { 
     // Textbox programming goes here 
     } 
    } 
} 

現在,當我想嘗試的東西有點不同與TexBox編程類似這種代碼

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

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

    private void textBox1_KeyDown(object sender, KeyEventArgs e) 
    { 
     // 
     // Detect the KeyEventArg's key enumerated constant. 
     // 
     if (e.KeyCode == Keys.Enter) 
     { 
     MessageBox.Show("You pressed enter! Good job!"); 
     } 
     else if (e.KeyCode == Keys.Escape) 
     { 
     MessageBox.Show("You pressed escape! What's wrong?"); 
     } 
    } 
    } 
} 

我不能運行的代碼,因爲文本框的狀態是

textBox1_KeyDown 

,而不是默認的是

textBox1_TextChanged 

現在的問題是,我怎麼去從默認彼此改變文本框的事件處理程序?

+2

你在說什麼?你會得到什麼錯誤? – SLaks

+1

呃,什麼? (還有6個去...) – nothrow

+0

我無法運行代碼,並且由於文本框的狀態是?這是什麼意思?你真正想做什麼? – coder

回答

6

KeyDownTextChanged不同事件

不是雙擊文本框輸入代碼事件,而是選擇屬性中的事件選項卡,然後雙擊要爲其編寫代碼的事件。

1

我想你正在尋找的是OnPreviewKeyDown事件......它告訴你接下來會發生什麼。如果你想繞過它的活動,你可以將「Handled」屬性設置爲true。

protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e) 
{ 
    var ue = e.OriginalSource as FrameworkElement; 

    if (e.Key == Key.Enter) 
    { 
     MessageBox.Show("You pressed enter! Good job!"); 
     e.Handled = true; // to tell event stack you've already taken care of this condition 
    } 
    else if (e.KeyCode == Keys.Escape) 
     MessageBox.Show("You pressed escape! What's wrong?"); 
}