Last active
August 22, 2018 11:59
-
-
Save guionardo/8233c5f2bd4de8e99c127a42b2c8b8df to your computer and use it in GitHub Desktop.
MessageBox with timeout (c#)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] | |
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName); | |
[DllImport("user32.Dll")] | |
static extern int PostMessage(IntPtr hWnd, UInt32 msg, int wParam, int lParam); | |
public static void MessageBox(string Text, string Caption = "", int timeOut = 0) | |
{ | |
if (Caption.Length == 0) | |
Caption = "MessageBox"; | |
if (timeOut <= 0) | |
{ | |
MessageBox.Show(Text, Caption, MessageBoxButtons.OK, MessageBoxIcon.Error); | |
return; | |
} | |
Caption += " " + string.Format("{0:X4}", DateTime.Now.Millisecond); // Force unique Window Caption | |
var timer = new System.Timers.Timer(5000) { AutoReset = false }; | |
timer.Elapsed += delegate | |
{ | |
const UInt32 WM_CLOSE = 0x0010; | |
IntPtr hWnd = FindWindowByCaption(IntPtr.Zero, Caption); | |
if (hWnd.ToInt32() != 0) PostMessage(hWnd, WM_CLOSE, 0, 0); | |
}; | |
timer.Enabled = true; | |
MessageBox.Show(Text, Caption, MessageBoxButtons.OK, MessageBoxIcon.Error); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment