2013-08-21 50 views
-2

我有數字按鈕,當按下時在不同的文本框中顯示數字。現在我的問題是,我想檢查哪些文本框具有焦點,以便按下的數字將被輸入到該文本框中。 我的代碼:在C#Winforms中設置焦點的文本框值

private void btn_one_Click(object sender, EventArgs e) 
{ 
    if (txt_one.Focused==true) 
    { 
     txt_one.Text += btn_one.Text; 
    } 
    else if (txt_two.Focused==true) 
    { 
     txt_two.Text += btn_one.Text; 
    } 
} 

現在我的問題是,上面的代碼不工作什麼是錯,什麼將是解決辦法嗎?我竟然用這樣的

private void btn_one_Click(object sender, EventArgs e) 
{ 
    if (txt_one.Focus()==true) 
    { 
     txt_one.Text += btn_one.Text; 
    } 
    else if (txt_two.Focus()=true) 
    { 
     txt_two.Text += btn_one.Text; 
    } 
} 

在這兩個文本在兩個文本框中輸入了上述情況。任何解決方案

+1

你真的不問問題。有什麼不工作? – xdumaine

+0

你的表單和一個實際問題的屏幕截圖將幫助 –

+0

顯示你的工作..無法獲得點。 –

回答

2

這個問題有點棘手(根據我的經驗處理Enter, Focus, LostFocus, Leave事件,所有這些事情有時會使你的頭部疼痛很多,如果可能的話,你應該避免與他們打交道),當你點擊你的Button時, Focused控制你可以知道確切的是ButtonActiveControl是訪問它的一個簡單方法)。因此,解決方案是我們必須記錄重點TextBox的軌跡,將其保存在參考中並在需要時使用。事實上,如果不是你TextBoxes的另一個控制的重點是,我們要變lastFocused重置爲空:

TextBox lastFocused; 
//Enter event handler for all your TextBoxes 
private void TextBoxes_Enter(object sender, EventArgs e){ 
    lastFocused = sender as TextBox; 
} 
//Click event handler for your button 
private void btn_one_Click(object sender, EventArgs e){ 
    if(lastFocused != null) lastFocused.Text += btn_one.Text; 
} 
+0

感謝您的答案@ King King,但上述代碼無法正常工作。 – ROM

+0

@ROM你知道如何爲** all **的文本框註冊'Enter'事件處理程序嗎? –

+0

對不起@王金我現在工作感謝千位先生。 – ROM