-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathhandle.h
56 lines (40 loc) · 1.71 KB
/
handle.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#pragma once
//#include <Wimgapi.h>
#define DefHandle(ClassName,type,hInvalidHandle,TCloseHandle)\
class ClassName\
{\
public:\
type hHandle;\
ClassName(type _hHandle = hInvalidHandle):hHandle(_hHandle){}\
~ClassName(){ Close(); }\
type* operator &(){ return &hHandle; } \
type operator=(type hHandle){ Close(); return this->hHandle = hHandle; }\
operator type() {return hHandle;}\
BOOL IsInvalid(){return hHandle == hInvalidHandle; }\
type Detach(){ type temp=hHandle; hHandle=hInvalidHandle;return temp; }\
HRESULT Close(){ if(IsInvalid()) return ERROR_INVALID_HANDLE; HRESULT hr=##TCloseHandle; if(hr==S_OK) hHandle=hInvalidHandle; return hr; }\
};
//关闭句柄形式1,直接返回 HRESULT
#define TCloseHandle1(_TCloseHandle) _TCloseHandle(hHandle)
//关闭句柄形式2,函数返回BOOL值,并通过GetLastError返回错误代码
#define TCloseHandle2(_TCloseHandle) _TCloseHandle(hHandle) ? S_OK : GetLastError()
//关闭句柄形式2,没有任何返回值
#define TCloseHandle3(_TCloseHandle) (_TCloseHandle(hHandle),S_OK)
//用于关闭RegOpenKey打开的句柄
DefHandle(CHKEY, HKEY, NULL, TCloseHandle1(RegCloseKey))
//用于关闭CreateFile打开的句柄
DefHandle(CHFile, HANDLE, INVALID_HANDLE_VALUE, TCloseHandle2(CloseHandle))
//用于关闭FindFirstFile打开的句柄
DefHandle(CHFileFind, HANDLE, INVALID_HANDLE_VALUE, TCloseHandle2(FindClose))
//自动关闭LoadLibrary的句柄
DefHandle(CHModule, HMODULE, NULL, TCloseHandle2(FreeLibrary))
//自动关闭互斥量的句柄
DefHandle(CHMutex, HANDLE, NULL, TCloseHandle2(CloseHandle))
typedef CHMutex CHEvent;
typedef CHMutex CHProcess;
#ifdef _WIMGAPI_H_
DefHandle(CHWim, HANDLE, NULL, TCloseHandle2(WIMCloseHandle))
#endif
#ifdef _INC_SETUPAPI
DefHandle(CHINF, HINF, INVALID_HANDLE_VALUE, TCloseHandle3(SetupCloseInfFile))
#endif