特定のテキストボックスにフォーカスがある場合にのみ、Windowsフォームにボタンを表示することはできますか?
このアプローチでそれを試しました:
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("OK");
}
private void textBox2_Enter(object sender, EventArgs e)
{
button3.Visible = true;
}
private void textBox2_Leave(object sender, EventArgs e)
{
button3.Visible = false;
}
ボタンのクリックが機能しないため、運がありません。テキストボックスがフォーカスを失った直後にボタンが非表示になり、button3_Click(/*...*/) { /*...*/ }
イベントが発生しなくなります。
今、私はそれをそのようにやっています:
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("OK");
}
private void textBox2_Enter(object sender, EventArgs e)
{
button3.Visible = true;
}
private void textBox2_Leave(object sender, EventArgs e)
{
//button3.Visible = false;
DoAfter(() => button3.Visible = false);
}
private async void DoAfter(Action action, int seconds = 1)
{
await Task.Delay(seconds*1000);
action();
}
フォームは1秒間待機してから、非表示になりbutton3
ます。
より良いアプローチはありますか?
フォーカスが特定のテキストボックスにある場合、またはフォーカスがボタンにある場合にのみボタンを表示したいと思います。
これを行うには、チェックすることができるFocused
のプロパティbutton3
でLeave
のイベントをtextBox2
、ボタンにフォーカスがない場合にのみボタンを非表示にします。ボタンがフォーカスを取得することに注意してください前Leave
のイベントtextBox2
発生します。
次にbutton3
、フォーカスを失い、フォーカスが以外の場所に移動するシナリオでは、ボタンを非表示にする必要がありますtextBox2
。ここでは、のLeave
イベントを処理し、フォーカスがない場合にbutton3
のみ非表示にすることで、まったく同じ手法を使用できます。button3
textBox2
次のコードは要件に適合している必要があります。
private void textBox2_Leave(object sender, EventArgs e)
{
if (!button3.Focused)
{
button3.Visible = false;
}
}
private void button3_Leave(object sender, EventArgs e)
{
if (!textBox2.Focused)
{
button3.Visible = false;
}
}
private void textBox2_Enter(object sender, EventArgs e)
{
button3.Visible = true;
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("Button clicked");
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加