I would like to present meaningful error messages when my program encounters Win32 errors. I call GetLastError
, and then FormatMessage
. But some of the error messages contain placeholders. For instance, ERROR_BAD_EXE_FORMAT
has the text:
%1 is not a valid Win32 application.
Presumably, the %1 is meant to be replaced by the name of the module which is not valid. How can I effect that replacement?
Note that I would ideally like a general solution because I note that there are many errors with placeholders. I can see the following messages in the documentation:
This error can be generated by a file that is a virus, worm, trojan, or another malware file. Often, this is caused because the virus scanner installed in the computer does not allow the file to be installed or run. Try scanning the file to verify it is not a virus or infected with a virus.
I think Raymond Chen effectively answers the question in a comment on his blog where he writes:
It bugs me too that system error messages contain
%1
insertions that you just have to "know" on a case-by-case basis.
ERROR_BAD_EXE_FORMAT
contains an insertion %1. You can replace that by using last parameter of FormatMessage()
. This code a little sample.
LPWSTR pMessage = L"%1";
DWORD_PTR pArgs[] = {(DWORD_PTR)L"My_Test_App.exe" };
TCHAR buffer[1024];
DWORD dwError = ERROR_BAD_EXE_FORMAT;
DWORD dwFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY;
DWORD dwResult = FormatMessage(dwFlags, pMessage, dwError, 0, buffer, 1024, (va_list*)pArgs);
if (dwResult)
{
//now, 'buffer' contains below message.
//
//My_Test_App.exe is not a valid Win32 application.
//
}
I know that some sytem error codes have insertion. I think we can't supply relevant argument for all of them. So, if I were you, I would like to use just system error code, not FormatMessage()
. Or, support argument list and FormatMessage()
for only some frequently system error code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With