C#实现winform自动关闭MessageBox对话框的方法
本文实例讲述了C#实现winform自动关闭MessageBox对话框的方法。分享给大家供大家参考。具体实现方法如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Runtime.InteropServices; namespaceWindowsApplication1 { publicpartialclassAutoDeleteMessageBox:Form { [DllImport("user32.dll",EntryPoint="FindWindow",CharSet=CharSet.Auto)] privateexternstaticIntPtrFindWindow(stringlpClassName,stringlpWindowName); [DllImport("user32.dll",CharSet=CharSet.Auto)] publicstaticexternintPostMessage(IntPtrhWnd,intmsg,IntPtrwParam,IntPtrlParam); publicconstintWM_CLOSE=0x10; publicAutoDeleteMessageBox() { InitializeComponent(); } privatevoidbutton1_Click(objectsender,EventArgse) { StartKiller(); MessageBox.Show("3秒钟后自动关闭MessageBox窗口","MessageBox"); } privatevoidStartKiller() { Timertimer=newTimer(); timer.Interval=3000;//3秒启动 timer.Tick+=newEventHandler(Timer_Tick); timer.Start(); } privatevoidTimer_Tick(objectsender,EventArgse) { KillMessageBox(); //停止Timer ((Timer)sender).Stop(); } privatevoidKillMessageBox() { //按照MessageBox的标题,找到MessageBox的窗口 IntPtrptr=FindWindow(null,"MessageBox"); if(ptr!=IntPtr.Zero) { //找到则关闭MessageBox窗口 PostMessage(ptr,WM_CLOSE,IntPtr.Zero,IntPtr.Zero); } } } }
希望本文所述对大家的C#程序设计有所帮助。