Winform MessageBox訊息彈窗如何實現自動關閉

小小邪發表於2024-10-12

使用了Windows API函式FindWindowSendMessage來查詢訊息框的視窗控制代碼併傳送關閉訊息

實現方法

 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();
        }

無法插入影片,改成執行的截圖

相關文章