首页 > Python基础教程 >
-
C#教程之WinForm 下实现一个自动关闭的MessageBox
Author: eaglet
WinForm 下我们可以调用MessageBox.Show 来显示一个消息对话框,提示用户确认等操作。在有些应用中我们需要通过程序来自动关闭这个消息对话框而不是由用户点击确认按钮来关闭。然而.Net framework 没有为我们提供自动关闭MessageBox 的方法,要实现这个功能,我们需要使用Window API 来完成。
首先我们需要找到这个消息对话框的窗口句柄,一个比较简单的方法就是用 FindWindow API 来查找对应的窗体句柄。



这个API调用可以通过窗口的类名或者窗口标题的名字来查找窗口句柄。
接下来我们还需要找到一个 API 来关闭对话框,这里我使用 EndDialog


有了这两个API函数,我们就可以来关闭消息对话框了。思路是在调用MessageBox.Show 前启动一个后台工作线程,这个工作线程等待一定时间后开始查找消息对话框的窗口句柄,找到后调用EndDialog API 函数关闭这个消息对话框。不过这个方法有个问题,就是如果同时又多个同名的消息对话框(可能不一定是这个应用的),这样做可能会关错窗口,如何解决这个问题,我还没有想出比较好的方法,如果大家有更好的方法解决这个问题,不妨一起讨论讨论。
我根据这个思路编写了延时关闭消息对话框的函数







这个函数中timeout 参数单位是毫秒,其他参数和MessageBox.Show的参数含义是一样的,这里不再详细说明。
这个函数中首先利用线程池调用一个工作线程 CloseMessageBox ,并将对话框的标题和延时时间通过CloseState这个类传递给CloseMessageBox函数。
CloseState 的定义如下:


































最后就是CloseMessageBox函数了,直接看代码吧













在屏幕的最前面弹一个消息框
有人要说了,弹一个ShowDialog不就完了吗?!或者MessageBox.Show("saaaaa");就可以达到目的。
但你要看到下面的情况,你就不这样说了。
我在C#中创建了一个Excel,每当我编辑一个值的时候,都会用C#代码判断这些值是否是有效的,当无效进就提醒他们。我用的就是MessageBox.Show("aaaaaaa");
但它不一定弹在最前面,因为它是C#的代码,故当Excel在最前面时,那个消息框是不能显示在最头面的。
用以下方法可以解决此问题:
MessageBox.Show("要弹的信息。", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information,MessageBoxDefaultButton.Button1, essageBoxOptions.DefaultDesktopOnly);
呵呵,虽然还是那个MessageBox.Show,但很多人都不知道呀。大家可以试试。
1
2
3
4
5
6
7
8
9
10
11
12
|
public const int WM_CLOSE = 0x10; [System.Runtime.InteropServices.DllImport( "user32.dll" , EntryPoint = "SendMessageA" )] public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); private void button1_Click( object sender, System.EventArgs e) { IntPtr hwnd_win; hwnd_win = FindWindow( null , "要找的窗体名" ); SendMessage(hwnd_win, WM_CLOSE, 0, 0); } |
查找窗口函数:
1
2
3
4
5
6
7
8
|
//查找窗体 [DllImport( "User32.dll" , EntryPoint = "FindWindow" )] private static extern int FindWindow( string lpClassName, string lpWindowName); static void Main() { //@Form1根据窗体的Text文本值获得窗体 int WINDOW_HANDLER = FindWindow( null , @"Form1" ); } |