HRESULT 数据类型和显示错误信息

本文详细介绍了HRESULT数据类型,包括其结构、用途及如何将其转换为错误消息。提供了两种将HRESULT转换为错误消息的方法:使用AMGetErrorText函数和FormatMessage函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HRESULT

What we should know about HRESULT ?
- HRSULT is a kind of Data Type ( Long 32bit) which is used for Windows.
- It is The return codes used by COM interfaces.
- To test an HRESULT value, use the FAILED and SUCCESSED macros.
- This type is declared in WinNT.h as follows:
   typedef LONG HRESULT;

Structure of COM Error Codes.
- HRESULT value has 32bits and is divided into 3 fields:  a severity code, a facility code, and an error code.

Bit    31 30 29 28 27, 26 25 24 ... 16, 15 14 ... 0
Field  S   R  C   N   r , Facility           , Error


Convert HRSULT retrun codes to error messages.
法(1) We can use  AMGetErrorText Function.
- Syntax :

DWORD AMGetErrorText (
	HRESULT hr,           // HRESULT value.
	TCHAR *pBuffer,     // Pointer to a character buffer that receives the error message.
 	DWORD MaxLen     // Number of characters in pBuffer.
);



- Requirement:
   Header: Errors.h (dshow.h)
   Lib : Quarz.lib
- Example:

void ShowError(HRESULT hr)
{
    if (FAILED(hr))
    {
        TCHAR szErr[MAX_ERROR_TEXT_LEN];
        DWORD res = AMGetErrorText(hr, szErr, MAX_ERROR_TEXT_LEN);
        if (res == 0)
        {
            StringCchPrintf(szErr, MAX_ERROR_TEXT_LEN, "Unknown Error: 0x%2x", hr);
        }
        MessageBox(0, szErr, TEXT("Error!"), MB_OK | MB_ICONERROR);
    }
}


 

 

//But , 我尝试上述,似乎总是找不到AMGetErrorText函数,找不到合适的H文件,可能需要安装额外的SDK.


法 (2) 

CString HrToMessage( HRESULT hr )
{
     LPVOID lpMsgBuf;
     CString strTmp;
     ::FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
         FORMAT_MESSAGE_FROM_SYSTEM,
         NULL,
         hr,
         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
         (LPTSTR) &lpMsgBuf,
         0,
         NULL );
     strTmp.Format( _T("%s"), (char *) lpMsgBuf );
     ::LocalFree( lpMsgBuf );
     return strTmp;
}


 

 

转载于:https://www.cnblogs.com/fdyang/archive/2012/06/06/2858738.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值