[英]MessageBox without focus on a MessageBoxButton
有沒有辦法在C#中顯示MessageBox而不關注消息框中的按鈕? 例如,以下代碼片段(無法正常工作):
MessageBox.Show("I should not have a button on focus",
"Test",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button3);
我想要的是顯示MessageBox而不關注[是]或[否]。 背景是客戶掃描幾個在和處有回車的條形碼。 因此,當消息框彈出並且他們掃描更多條形碼而沒有注意到消息框時,他們“按下”按鈕。
那么你可以通過一些技巧來做到這一點。
[DllImport("user32.dll")]
static extern IntPtr SetFocus(IntPtr hWnd);
private void button1_Click(object sender, EventArgs e)
{
//Post a message to the message queue.
// On arrival remove the focus of any focused window.
//In our case it will be default button.
this.BeginInvoke(new MethodInvoker(() =>
{
SetFocus(IntPtr.Zero);//Remove the focus
}));
MessageBox.Show("I should not have a button on focus",
"Test",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button3);
}
請注意,上面的代碼假定在調用BeginInvoke
時會顯示MessageBox
並且它會使按鈕聚焦。 根據我的知識,情況通常如此。 如果您想確保消息框已經顯示,您可以使用此代碼查找它,然后您可以刪除焦點。
使用標准MessageBox是不可能的 - 如果你想要這個功能,你需要實現自己的。
看到這里是為了幫助您入門
msg
button1
,其text屬性設置為OK
Visible
屬性設置為false
的textBox1
在msg_FormLoad()
添加此代碼:
txtBox1.Focus();
將此代碼添加到buton1_Click
:
this.Close();
無論何時您想要顯示您的信息,您都可以:
msg msgBox = new msg(); msgBox.ShowDialog();
PS:沒有測試,因為目前缺乏IDE,但我想它可以調整到很少工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.