我不时使用 MessageBox
为用户弹出警报消息。我的特定应用程序可以设置为远程运行,因此有时用户在计算机前,有时用户可能数小时甚至数天不在计算机前。有时我会使用 MessageBox
弹出警报消息,但一段时间后警报不再相关。例如,我弹出一个警告,提示某项任务由于未满足某些条件而无法完成。几分钟后,该条件得到满足,任务开始。 MessageBox
不再相关。
在消息不再相关的情况下,我希望能够以编程方式关闭 MessageBox
。这可能吗?目前我在一个线程中创建我的 MessageBox
对象:
new Thread(() => MessageBox.Show("Some text", "Some caption")).Start();
我这样做是为了让应用程序可以继续在后台工作,而不会被 MessageBox
暂停。有什么建议吗?
最佳答案
这对我有用
public partial class Form1 : Form
{
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
[DllImport("user32.Dll")]
static extern int PostMessage(IntPtr hWnd, UInt32 msg, int wParam, int lParam);
const UInt32 WM_CLOSE = 0x0010;
Thread thread;
public Form1()
{
InitializeComponent();
thread = new Thread(ShowMessageBox);
thread.Start();
}
void CloseMessageBox()
{
IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, "Caption");
if (hWnd != IntPtr.Zero)
PostMessage(hWnd, WM_CLOSE, 0, 0);
if (thread.IsAlive)
thread.Abort();
}
static void ShowMessageBox()
{
MessageBox.Show("Message", "Caption");
}
}
现在您可以使用 CloseMessageBox()
关闭消息框。
但请记住,CloseMessageBox()
和 ShowMessageBox()
中的标题必须相同!
也许通过一个全局变量,但这取决于你。
关于c# - 在没有用户输入的情况下以编程方式拆卸 MessageBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19635749/