C++ Windows messages

I find myself always wanting to pair asserts, exceptions and log messages with sprintf. So here’s some utilities using OutputDebugString and MessageBox for future reference!

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
#include <Windows.h>
#include <cstdio>

void _Message(char* title, unsigned int flags, char* fmt, va_list args)
{
	int size;
#pragma warning(suppress:28719)    // 28719
	size = vsnprintf(nullptr, 0, fmt, args);

	char* message = new char[size];
	vsnprintf(message, size, fmt, args);

	if (IsDebuggerPresent())
		OutputDebugStringA(message);
	else
		MessageBoxA(0, message, title, flags);
	delete message;
}

void Info(char* fmt, ...)
{
	va_list args;
	__crt_va_start(args, fmt);
	_Message("Info", MB_OK | MB_ICONINFORMATION, fmt, args);
	__crt_va_end(args);
}

void Warning(char* fmt, ...)
{
	va_list args;
	__crt_va_start(args, fmt);
	_Message("Warning", MB_OK | MB_ICONWARNING, fmt, args);
	__crt_va_end(args);
	if (IsDebuggerPresent())
		DebugBreak();
}

void Error(char* fmt, ...)
{
	va_list args;
	__crt_va_start(args, fmt);
	_Message("Error", MB_OK | MB_ICONEXCLAMATION, fmt, args);
	__crt_va_end(args);
	if (IsDebuggerPresent())
		DebugBreak();
}

void Fatal(char* fmt, ...)
{
	va_list args;
	__crt_va_start(args, fmt);
	_Message("Error", MB_OK | MB_ICONEXCLAMATION, fmt, args);
	__crt_va_end(args);
	if (IsDebuggerPresent())
		DebugBreak();
	else
		ExitProcess(0);
}

void Assert(bool expression)
{
	if (expression)
		return;
	if (IsDebuggerPresent())
		DebugBreak();
}

void Assert(bool expression, char* fmt, ...)
{
	if (expression)
		return;
	va_list args;
	__crt_va_start(args, fmt);
	_Message("Error", MB_OK | MB_ICONEXCLAMATION, fmt, args);
	__crt_va_end(args);
	if (IsDebuggerPresent())
		DebugBreak();
}

void AssertFatal(bool expression)
{
	if (expression)
		return;
	if (IsDebuggerPresent())
		DebugBreak();
	else
		ExitProcess(0);
}

void AssertFatal(bool expression, char* fmt, ...)
{
	if (expression)
		return;
	va_list args;
	__crt_va_start(args, fmt);
	_Message("Error", MB_OK | MB_ICONEXCLAMATION, fmt, args);
	__crt_va_end(args);
	if (IsDebuggerPresent())
		DebugBreak();
	else
		ExitProcess(0);
}

Leave a Reply

Your email address will not be published. Required fields are marked *