首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

C# WinForm 自動關閉 MessageBox:Timer + FindWindow + PostMessage 實作

     編輯:更多程式設計知識

MessageBox.Show 為阻塞式對話框,無內建自動關閉功能。利用 Timer 定時呼叫 Win32 API FindWindow 尋找視窗並發送 WM_CLOSE 訊息實現定時自動關閉。

完整程式碼


using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication1 {
    public partial class AutoDeleteMessageBox : Form {
        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);

        private const int WM_CLOSE = 0x10;

        public AutoDeleteMessageBox() {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e) {
            StartKiller();
            MessageBox.Show("3秒鐘後自動關閉MessageBox視窗", "MessageBox");
        }

        private void StartKiller() {
            Timer timer = new Timer();
            timer.Interval = 3000;
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e) {
            KillMessageBox();
            ((Timer)sender).Stop();
        }

        private void KillMessageBox() {
            IntPtr ptr = FindWindow(null, "MessageBox");
            if (ptr != IntPtr.Zero) {
                PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            }
        }
    }
}

原理解析

  • FindWindow(null, "MessageBox"):依標題尋找視窗控制碼。
  • PostMessage(hWnd, WM_CLOSE, ...):發送關閉訊息,非阻塞。
  • Timer:在獨立執行緒定時觸發,避免阻塞 UI 主執行緒。

擴充建議

  • 封裝為靜態工具方法 MessageBoxEx.ShowWithTimeout(text, caption, timeoutMs)。
  • 支援自訂視窗標題以精確定位。
  • 考慮使用 Task.Delay + async/await 簡化非同步邏輯(.NET 4.5+)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved