-
-
Save bytequill/22ae4fc20c1461512fbf23e3ff6f5e0c to your computer and use it in GitHub Desktop.
Win32 API MessageBox() in Golang
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
import ( | |
"syscall" | |
"unsafe" | |
) | |
func newGoWinAPI() GoWinAPI { | |
return GoWinAPI{ | |
winAPI: NewWinAPI(), | |
} | |
} | |
// Struct with simplified WinAPI bindings | |
type GoWinAPI struct { | |
winAPI WinAPI | |
} | |
func (api GoWinAPI) MessageBox(windowTitle string, windowContent string, flags uint) int { | |
// For reference on flags see: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messageboxw | |
return api.winAPI.MessageBoxW( | |
0, // NULL hwnd | |
windowContent, | |
windowTitle, | |
flags, | |
) | |
} | |
func NewWinAPI() WinAPI { | |
return WinAPI{ | |
user32dll: syscall.NewLazyDLL("user32.dll"), | |
} | |
} | |
// Struct with raw WinAPI bindings | |
type WinAPI struct { | |
user32dll *syscall.LazyDLL | |
} | |
// MB_BUTTONS | |
const MB_OK = 0x0 | |
const MB_OKCANCEL = 0x1 | |
const MB_ABORTRETRYIGNORE = 0x2 | |
const MB_YESNOCANCEL = 0x3 | |
const MB_YESNO = 0x4 | |
const MB_RETRYCANCEL = 0x5 | |
const MB_CANCELTRYCONTINUE = 0x6 | |
// MB_ICONS | |
const MB_ICONNONE = 0x00 | |
const MB_ICONSTOP = 0x10 | |
const MB_ICONERROR = 0x10 | |
const MB_ICONHAND = 0x10 | |
const MB_ICONQUESTION = 0x20 | |
const MB_ICONEXCLAMATION = 0x30 | |
const MB_ICONWARNING = 0x30 | |
const MB_ICONINFORMATION = 0x40 | |
const MB_ICONASTERISK = 0x40 | |
// MB_DEFBUTTON | |
const MB_DEFBUTTON1 = 0x000 | |
const MB_DEFBUTTON2 = 0x100 | |
const MB_DEFBUTTON3 = 0x200 | |
const MB_DEFBUTTON4 = 0x300 | |
// MB_MODALITY | |
const MB_APPLMODAL = 0x0000 | |
const MB_SYSTEMMODAL = 0x1000 | |
const mb_TASKMODAL = 0x2000 | |
func (api WinAPI) MessageBoxW(hwnd uintptr, lpText string, lpCaption string, flags uint) int { | |
/* https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messageboxw | |
int MessageBoxW( | |
[in, optional] HWND hWnd, | |
[in, optional] LPCWSTR lpText, | |
[in, optional] LPCWSTR lpCaption, | |
[in] UINT uType | |
);*/ | |
response, _, _ := api.user32dll.NewProc("MessageBoxW").Call( | |
uintptr(hwnd), | |
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(lpText))), | |
uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(lpCaption))), | |
uintptr(flags), | |
) | |
return int(response) | |
} | |
// MessageBoxPlain of Win32 API. | |
func MessageBoxPlain(title, caption string) int { | |
const ( | |
NULL = 0 | |
MB_OK = 0 | |
) | |
return MessageBox(NULL, caption, title, MB_OK) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment