处理对象

2018-07-13 02:37:00来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

在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);

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:STL之set的应用

下一篇:基础篇(1):c++程序基本结构