Skip to content

Instantly share code, notes, and snippets.

@guionardo
Last active August 22, 2018 11:59
Show Gist options
  • Save guionardo/8233c5f2bd4de8e99c127a42b2c8b8df to your computer and use it in GitHub Desktop.
Save guionardo/8233c5f2bd4de8e99c127a42b2c8b8df to your computer and use it in GitHub Desktop.
MessageBox with timeout (c#)
[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