Skip to content

Instantly share code, notes, and snippets.

@roydejong
Last active June 4, 2024 09:03
Show Gist options
  • 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) { }
}
}
@stalkeriy2010
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 [email protected]

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