Windows API Programming----converting error codes to error description information

Source: Internet
Author: User

Windows programming sometimes generates an error by calling a function, and calling the GetLastError () function can get an error code. If the error code is 0, there is no error, and if the error code is not 0, there is an error.

The error code does not make it easy for programmers or users to intuitively understand what is going wrong. Visual Studio 2015 (or previous version) provides an external tool for error lookup, and you can enter the error code to see what went wrong.

  

  

If you want to see the error message in your program code, you can write the following function:

#include <iostream>#include<Windows.h>using namespacestd;voidWinerr ();intMainintargcChar*argv[]) {System ("haha");    Winerr (); System ("Pause"); return 0;}voidWinerr () {Char* Win_msg =NULL; DWORD Code=GetLastError (); if(Code = =0) {cout<<"Error"<<code<<": No error!\n"; return; }            Else    {        //Get error messageFormatMessage (Format_message_allocate_buffer | Format_message_from_system, NULL, Code, MAKELANGID (Lang_neutral, Sublang_default), (LPTSTR) &win_msg,0, NULL); if(Win_msg! =NULL) {cout<<"Error"<< Code <<":"<< win_msg <<Endl;        LocalFree (WIN_MSG); }    }    //to make the function call does not affect the result of subsequent function calls to the GetLastError () functionSetLastError (code);}

Test results:

Windows API Programming----converting error codes to error description information

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.