使用了Windows API函数FindWindow
和SendMessage
来查找消息框的窗口句柄并发送关闭消息
实现方法
public class AutoClosingMessageBox { System.Threading.Timer _timeoutTimer; string _caption; AutoClosingMessageBox(string text, string caption, int timeout) { _caption = caption; _timeoutTimer = new System.Threading.Timer(OnTimerElapsed, null, timeout, System.Threading.Timeout.Infinite); // 显示消息框 MessageBox.Show(text, caption); } public static void Show(string text, string caption, int timeout) { new AutoClosingMessageBox(text, caption, timeout); } void OnTimerElapsed(object state) { IntPtr mbWnd = FindWindow(null, _caption); if (mbWnd != IntPtr.Zero) SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); _timeoutTimer.Dispose(); } const int WM_CLOSE = 0x0010; [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)] static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); }
调用方法
AutoClosingMessageBox.Show("这是一条自动关闭的消息", "消息标题", 3000); // 3000毫秒后关闭
实现效果
自己建一个winform窗体,拉一个button控件,在按钮的实现方法写入调用代码
如下按钮的实现方法
/// <summary> /// 清空扫描结果事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnClear_Click(object sender, EventArgs e) { AutoClosingMessageBox.Show("这是一条自动关闭的消息", "消息标题", 3000); // 3000毫秒后关闭 //清空输入框并获取焦点 clearScanCode(); } /// <summary> /// 清空输入框 /// </summary> private void clearScanCode() { this.txtScanCode.Text = ""; this.txtScanCode.Focus(); }
标签:IntPtr,MessageBox,AutoClosingMessageBox,string,System,caption,关闭,弹窗,Winform From: https://www.cnblogs.com/xielong/p/18460751