2017-07-11 16 views
0

我想要得到哪個文本框被聚焦之前,我點擊按鈕。如何在單擊按鈕之前獲取哪個文本框已被集中?

但是當我按下按鈕時,焦點將被改變爲這個按鈕。

那麼,我該怎麼辦?

或者有類似之前的事件點擊按鈕????

非常感謝~~~

+0

順便說一句,我不想使用TextBox.GotFocus來保存文本框。 因爲我會在運行時創建新的文本框。 –

+1

您可以爲您的控件添加一個'LostFocus'事件處理程序,並在每次觸發時爲事件發件人設置一個私有變量'previousFocusedControl'。這將是跟蹤以前控制的一種方式。 – InBetween

+0

你解決了什麼問題?這個按鈕假設要做什麼? – Sinatr

回答

0

我不知道它是否能在現實情況,但一個棘手的方式使用本

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

      this.button1.MouseEnter += button1_MouseEnter; 
     } 

     void button1_MouseEnter(object sender, EventArgs e) 
     { 
      focusedTextBox = null; 

      if (this.textBox1.Focused) 
      { 
       focusedTextBox = this.textBox1; 
      } 

     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      if (focusedTextBox != null) 
      { 
       MessageBox.Show(focusedTextBox.Name + " has focuse"); 
      } 
     } 

     TextBox focusedTextBox; 

    } 
} 
+0

謝謝,Bahrom。 你的想法與我的相符。 當我問到問題後,我試試。 但我用foreach來查找文本框。 –

0

我認爲你將不得不繼續跟蹤,當你想跟蹤每個控制重點的變化。

How track when any child control gets or loses the focus in WinForms?

別看只對選定的答案,有一個upvoted答案是談論Enter和Leave,看起來有前途的事件。

下面是一些適用於我的示例代碼,您可以根據需要進行調整。

public Form1() 
    { 
    InitializeComponent(); 
    this.textBox1.Leave += Form1_Leave; 
    this.textBox2.Leave += Form1_Leave; 
    this.textBox3.Leave += Form1_Leave; 
    } 


    public object LastSender { get; set; } 

    private void Form1_Leave(object sender, EventArgs e) 
    { 
    LastSender = sender; 
    } 


    private void button1_Click(object sender, EventArgs e) 
    { 
    var lastTextBox = LastSender as TextBox; 
    if (lastTextBox == null) return; 
    MessageBox.Show(lastTextBox.Name); 
    } 

好的部分是,你可以訂閱所有事件到相同的方法。所以,當你動態地添加一個新的控制,你可以做:

newTextBox.Leave += Form1_Leave; 
+0

謝謝你,德里克。 但我不想在文本框中設置任何事件進行記錄。 –

相關問題