我正在制作一個計算器。對于鍵入數字的按鈕,我寫了一個條件,如果焦點在文本框 1 上,它將在那里輸入文本,如果不是,它將輸入文本框 2。但不幸的是,代碼沒有作業,我不明白這個問題。(WindosForm(.Net 框架))
if (textBox1.Focus() == true)
{
textBox1.Text = textBox1.Text "1";
}
else
{
textBox2.Text = textBox2.Text "1";
}
uj5u.com熱心網友回復:
訂閱兩個文本框的“Enter”事件并保存。對兩個文本框使用相同的方法。
TextBox focusedTB;
private void textBox_Enter(object sender, EventArgs e)
{
focusedTB = sender as TextBox;
}
...
this.textBox1.Enter = new System.EventHandler(this.textBox_Enter);
...
this.textBox2.Enter = new System.EventHandler(this.textBox_Enter);
現在您知道最后一個獲得焦點的文本框了。
private void button1_Click(object sender, EventArgs e)
{
focusedTB.Text = "1";
}
uj5u.com熱心網友回復:
您的代碼似乎正在嘗試檢查控制元件是否具有焦點。正確的做法是:
if (textBox1.Focused)
{
// Because 'Focused' is a property. 'Focus()' is a method.
textBox1.Text = textBox1.Text "1";
}
.
.
.
你的問題的答案為什么我不能改變焦點?是textBox1每次呼叫時都會獲得焦點:
if (textBox1.Focus())
正如其中一條評論所述,以下是 Focus 方法的作業原理:
// Summary:
// Sets input focus to the control.
//
// Returns:
// true if the input focus request was successful; otherwise, false.
[EditorBrowsable(EditorBrowsableState.Advanced)]
public bool Focus();
注意:這是元資料的復制粘貼,您可以通過右鍵單擊Focus()代碼并選擇轉到定義然后展開定義來查看。
uj5u.com熱心網友回復:
我想你在談論 Windows Form 嗎?您不能這樣管理,而是使用文本框的事件“Enter”,當您在文本框內單擊時,您將焦點放在該文本框上,您可以在其中執行任何操作。在這里,我將正確的焦點 TextBox 放在一個變數中。
private TextBox _textBoxFocused; //this is always the righ TextBox
private void textBox1_Enter(object sender, EventArgs e)
{
_textBoxFocused = textBox1;
}
private void textBox2_Enter(object sender, EventArgs e)
{
_textBoxFocused = textBox2;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/484669.html
上一篇:JPACriteriaQuery:如何為multiSelect選擇默認值
下一篇:請確保指定位置存在聲音檔案
