0
votes

Should I check the CreateWindowEx() function call for failure? and what should I do if it fails, I mean if I am creating a group of buttons and one of the function calls failed, should I close the application all together? I mean the absence of just one button can make the application useless.

1
Yes you should check if you get a valid handle, if the function returns NULL something went wrong and you can then use GetLastError() to get an error code. What action you take depends on why the function failes. - Cyclonecode
What if I don't get a valid handle (which means I suppose the button was not created), should I display an error message and close the application? - user4182981
the absence of just one button can make the application useless there is your answer -> inform the user with MessageBox that button creation failed and close the app. You could write a small log ( as a .txt file ) at least with relevant information. That way user can submit this "error report" and you would have something as a guidance when you do debugging... - AlwaysLearningNewStuff
I think that still depends on why CreateWindowEx() fails. You can get a more readable error message using FormatMessage() with the error code returned from GetLastError(). - Cyclonecode

1 Answers

2
votes

I think you always should check the return value from CreateWindowEx(). If the return value is NULL then you know that something went wrong and you can take some action in response to that. What you do when something goes wrong is up to you, for instance you could display a message box with a description of the error or you could log the error to a file, etc:

// Try to create your window
HWND hwnd = CreateWindowEx(...);

// check if the handle is valid
if(hwnd == NULL) {

   // display a MessageBox() with a descriptive error message
   LPVOID lpErrorMessage;
   DWORD dwErrorCode = GetLastError();

   FormatMessage(
      FORMAT_MESSAGE_ALLOCATE_BUFFER | 
      FORMAT_MESSAGE_FROM_SYSTEM |
      FORMAT_MESSAGE_IGNORE_INSERTS,
      NULL,
      dwErrorCode,
      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
      (LPTSTR) &lpErrorMessage,
      0, NULL 
  );
  MessageBox(NULL, (LPCTSTR)lpErrorMessage, TEXT("Error"), MB_OK);

  // don't forget to free the buffer allocated by FormatMessage
  LocalFree(lpErrorMessage);

  // terminate process
  ExitProcess(dwErrorCode);
}