2016-06-28 23 views
0

我在形式TextBox1中1和TextBox 2個文本框(是啊是相當懶惰) 和創建副本的任務,並粘貼類似功能的應用程序 (實踐原因)如何獲得有效的TextBox Windows窗體

,但我不知道該計劃將如何確定哪些文本框是目前活躍的一個

public partial class Form1 : Form 
    { 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 

    } 

    private void Form1_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.KeyCode == Keys.F1) //Copy 
     { 

     } 
     else if (e.KeyCode == Keys.F2) //Paste 
     { 

     } 
    } 
} 
+0

也許IsFocused? –

回答

0

你必須給發件人轉換爲TextBox,並得到它的名字或任何識別您的文本框。 就做負責任地使用asvar textBox = sender as TextBox,然後檢查其空

編輯:事件處理程序必須被分配到兩個TextBox元素不是形式

+0

我是否必須爲我的每個文本框執行此操作?...... –

+1

只有在將「KeyDown」處理程序分配給「TextBox」「KeyDown」事件時,此功能纔有效。從它的名字我認爲它被分配到'Form'事件,所以'sender'永遠是'Form',而不是'TextBox'。 –

+0

@kennedydelrosario是的,你必須將這個事件賦予每個「TextBox」 – Alex

0

您可以確定哪些TextBox通過使用ContainsFocus屬性激活:

private void Form1_KeyDown(object sender, KeyEventArgs e) 
{ 
    TextBox activeTextBox = textBox1.ContainsFocus 
        ? textBox1 
        : (textBox2.ContainsFocus ? textBox2 : null);  

    if (e.KeyCode == Keys.F1) //Copy 
    { 

    } 
    else if (e.KeyCode == Keys.F2) //Paste 
    { 

    } 
} 

或可替代的Form.ActiveControl屬性:

private void Form1_KeyDown(object sender, KeyEventArgs e) 
{ 
    TextBox activeTextBox = ActiveControl as TextBox; 

    if (e.KeyCode == Keys.F1) //Copy 
    { 

    } 
    else if (e.KeyCode == Keys.F2) //Paste 
    { 

    } 
} 
相關問題