处理对象
程序员文章站
2023-12-31 22:12:10
在Windows编程中,HANDLE根据不同的对象有不同的返回值,例如普通处理对象的无效值是NULL、 文件处理对象的无效值是INVALID_HANDLE_VALUE。 现对HANDLE进行封装,方便使用和扩展。 头文件 实现文件 使用例子: ......
在Windows编程中,HANDLE根据不同的对象有不同的返回值,例如普通处理对象的无效值是NULL、
文件处理对象的无效值是INVALID_HANDLE_VALUE。
现对HANDLE进行封装,方便使用和扩展。
头文件
#pragma once class CNullHandle { public: CNullHandle(HANDLE h = NULL); ~CNullHandle(); void operator = (HANDLE h); void Attach(HANDLE h); void Close(); BOOL IsNull() const; operator HANDLE () const; public: HANDLE m_handle; }; class CInvalidHandle { public: CInvalidHandle(HANDLE h = INVALID_HANDLE_VALUE); ~CInvalidHandle(); void operator = (HANDLE h); void Attach(HANDLE h); void Close(); BOOL IsNull() const; operator HANDLE () const; public: HANDLE m_handle; }; template<class T> class CWinHandle { public: CWinHandle(T h = NULL) :m_h(h) { } ~CWinHandle() { } void operator = (HANDLE h) { m_h = h; } void Attach(HANDLE h) { m_h.Attach(h); } void Close() { m_h.Close(); } BOOL IsNull() const { return m_h.IsNull(); } operator HANDLE () const { return m_h; } private: T m_h; };
实现文件
#include "stdafx.h" #include "WinHandle.h" CNullHandle::CNullHandle(HANDLE h/* = NULL*/) :m_handle(h) { } CNullHandle::~CNullHandle() { Close(); } void CNullHandle::operator = (HANDLE h) { Attach(h); } void CNullHandle::Attach(HANDLE h) { if (NULL != m_handle && m_handle != h) { CloseHandle(m_handle); m_handle = h; } } void CNullHandle::Close() { if (NULL != m_handle) { CloseHandle(m_handle); m_handle = NULL; } } BOOL CNullHandle::IsNull() const { return (NULL == m_handle); } CNullHandle::operator HANDLE () const { return m_handle; } CInvalidHandle::CInvalidHandle(HANDLE h/* = INVALID_HANDLE_VALUE*/) :m_handle(h) { } CInvalidHandle::~CInvalidHandle() { Close(); } void CInvalidHandle::operator = (HANDLE h) { Attach(h); } void CInvalidHandle::Attach(HANDLE h) { if (INVALID_HANDLE_VALUE != m_handle && m_handle != h) { CloseHandle(m_handle); m_handle = h; } } void CInvalidHandle::Close() { if (INVALID_HANDLE_VALUE != m_handle) { CloseHandle(m_handle); m_handle = INVALID_HANDLE_VALUE; } } BOOL CInvalidHandle::IsNull() const { return (INVALID_HANDLE_VALUE == m_handle); } CInvalidHandle::operator HANDLE () const { return m_handle; }
使用例子:
CInvalidHandle invalidH; CWinHandle<CInvalidHandle> hSnapshot(invalidH); hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
CWinHandle<CNullHandle> hProcess; hProcess = OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_TERMINATE|PROCESS_VM_READ, FALSE, pe32.th32ProcessID);