Skip to content

Instantly share code, notes, and snippets.

@roydejong
Last active March 31, 2024 15:53
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roydejong/130a91e1835154a3acaeda78c9dfbbd7 to your computer and use it in GitHub Desktop.
Save roydejong/130a91e1835154a3acaeda78c9dfbbd7 to your computer and use it in GitHub Desktop.
Unity: NativeWinAlert (Windows MessageBox / Alert Dialog for Unity games)
using System;
using System.Runtime.InteropServices;
/// <see>https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-messagebox</see>
public static class NativeWinAlert
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern System.IntPtr GetActiveWindow();
public static System.IntPtr GetWindowHandle()
{
return GetActiveWindow();
}
[DllImport("user32.dll", SetLastError = true)]
static extern int MessageBox(IntPtr hwnd, String lpText, String lpCaption, uint uType);
/// <summary>
/// Shows Error alert box with OK button.
/// </summary>
/// <param name="text">Main alert text / content.</param>
/// <param name="caption">Message box title.</param>
public static void Error(string text, string caption)
{
try
{
MessageBox(GetWindowHandle(), text, caption, (uint)(0x00000000L | 0x00000010L));
}
catch (Exception ex) { }
}
}
@roydejong
Copy link
Author

roydejong commented Jul 26, 2018

This is the equivalent of using a MessageBox in a .NET Windows Forms application, except falling back to the native counterpart.

Example use:

NativeWinAlert.Error("Something went wrong.", "Message title");

Notes:

  • Alert dialogs are synchronous and blocking. I only use them for critical startup errors (e.g. Steamworks not initializing properly) to inform the user before quitting the app.
  • This is (obviously) not cross platform at all, as it invokes native Windows APIs.
  • It shouldn't break if there is different foreground window (not unity) as GetActiveWindow "[retrieves] the window handle to the active window attached to the calling thread's message queue".

To see all style / button options for the Messagebox:
https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-messagebox

@stoilkr2010
Copy link

Works great :) This was quite weird to work with especially that System.Windows.Forms.dll wouldn't even import, thank you.

@Mellurboo
Copy link

Thank you so much for this, I have credited you in the source and will in any release its used in!
if you want it removed you can contact me on this post or hit me up business.selectstudios@gmail.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment