Last active
June 4, 2024 09:03
-
-
Save roydejong/130a91e1835154a3acaeda78c9dfbbd7 to your computer and use it in GitHub Desktop.
Unity: NativeWinAlert (Windows MessageBox / Alert Dialog for Unity games)
This file contains 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
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) { } | |
} | |
} |
Works great :) This was quite weird to work with especially that System.Windows.Forms.dll wouldn't even import, thank you.
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
This is the equivalent of using a MessageBox in a .NET Windows Forms application, except falling back to the native counterpart.
Example use:
Notes:
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