共用方式為


查找錯誤代碼的文本

有時必須顯示與網路相關函式傳回之錯誤碼相關聯的錯誤文字。 您可能需要使用系統所提供的網路管理功能來執行這項工作。

這些訊息的錯誤文字位於名為 Netmsg.dll的訊息數據表檔案中,該檔案位於 \system32 %systemroot%。 此檔案包含範圍NERR_BASE (2100) 到 MAX_NERR(NERR_BASE+899) 的錯誤訊息。 這些錯誤碼定義於 SDK 頭檔 lmerr.h 中。

LoadLibraryLoadLibraryEx 函式可以載入 Netmsg.dll。 FormatMessage 函式會將錯誤碼對應至訊息正文,給定的模組句柄指向 Netmsg.dll 檔案。

下列範例說明如何顯示與網路管理功能相關聯的錯誤文字,以及顯示與系統相關錯誤碼相關聯的錯誤文字。 如果提供的錯誤號碼位於特定範圍內,則會載入 netmsg.dll 訊息模組,並使用 FormatMessage 函式查閱指定的錯誤號碼。

#include <windows.h>
#include <stdio.h>

#include <lmerr.h>

void
DisplayErrorText(
    DWORD dwLastError
    );

#define RTN_OK 0
#define RTN_USAGE 1
#define RTN_ERROR 13

int
__cdecl
main(
    int argc,
    char *argv[]
    )
{
    if(argc != 2) {
        fprintf(stderr,"Usage: %s <error number>\n", argv[0]);
        return RTN_USAGE;
    }

    DisplayErrorText( atoi(argv[1]) );

    return RTN_OK;
}

void
DisplayErrorText(
    DWORD dwLastError
    )
{
    HMODULE hModule = NULL; // default to system source
    LPSTR MessageBuffer;
    DWORD dwBufferLength;

    DWORD dwFormatFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_IGNORE_INSERTS |
        FORMAT_MESSAGE_FROM_SYSTEM ;

    //
    // If dwLastError is in the network range, 
    //  load the message source.
    //

    if(dwLastError >= NERR_BASE && dwLastError <= MAX_NERR) {
        hModule = LoadLibraryEx(
            TEXT("netmsg.dll"),
            NULL,
            LOAD_LIBRARY_AS_DATAFILE
            );

        if(hModule != NULL)
            dwFormatFlags |= FORMAT_MESSAGE_FROM_HMODULE;
    }

    //
    // Call FormatMessage() to allow for message 
    //  text to be acquired from the system 
    //  or from the supplied module handle.
    //

    if(dwBufferLength = FormatMessageA(
        dwFormatFlags,
        hModule, // module to get message from (NULL == system)
        dwLastError,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // default language
        (LPSTR) &MessageBuffer,
        0,
        NULL
        ))
    {
        DWORD dwBytesWritten;

        //
        // Output message string on stderr.
        //
        WriteFile(
            GetStdHandle(STD_ERROR_HANDLE),
            MessageBuffer,
            dwBufferLength,
            &dwBytesWritten,
            NULL
            );

        //
        // Free the buffer allocated by the system.
        //
        LocalFree(MessageBuffer);
    }

    //
    // If we loaded a message source, unload it.
    //
    if(hModule != NULL)
        FreeLibrary(hModule);
}

編譯此程序之後,您可以將錯誤碼號碼插入為自變數,而且程式會顯示文字。 例如:

C:\> netmsg 2453
Could not find domain controller for this domain