#include "stdafx.h" #include "CTwainMutex.h" CTwainMutex::CTwainMutex(void) { m_hTwainMutex=NULL; m_bInited=FALSE; memset(m_sTwainMutex,0,sizeof(m_sTwainMutex)); } CTwainMutex::~CTwainMutex(void) { if (m_hTwainMutex!=NULL) { CloseHandle(m_hTwainMutex); m_hTwainMutex=NULL; } } BOOL CTwainMutex::CreatTwainMutex(TCHAR *str_Mutex) { TCHAR mutexName[MAX_PATH]={0}; DWORD error_code=0; HANDLE hMutex=NULL; BOOL b_ret=FALSE; if (m_hTwainMutex!=NULL) { return b_ret; } _tcscpy(mutexName,str_Mutex); hMutex=CreateMutex(NULL,FALSE,mutexName); if (hMutex!=NULL) { error_code=GetLastError(); if (error_code==ERROR_ALREADY_EXISTS||error_code==ERROR_ACCESS_DENIED) { MessageBox(NULL, _T("设备已被其他程序占用,请关闭占用程序之后再重试!"), _T("提示"),MB_OK|MB_ICONWARNING); b_ret=CloseHandle(hMutex); if (!b_ret) { MessageBox(NULL, TEXT("资源释放异常"), 0, MB_ICONWARNING); } hMutex=NULL; return FALSE; } else { if (m_hTwainMutex!=NULL) { b_ret=CloseHandle(m_hTwainMutex); if (!b_ret) { return FALSE; } m_hTwainMutex=NULL; } m_hTwainMutex=hMutex; b_ret=TRUE; } return b_ret; } else { MessageBox(NULL, TEXT("程序初始化错误"), 0, MB_ICONWARNING); } return b_ret; } BOOL CTwainMutex::CheckExistTwainMutex(TCHAR* str_Mutex) { TCHAR szMutexName[MAX_PATH] = {0}; DWORD error_code = 0; BOOL b_ret = FALSE; HANDLE hMutex = NULL; if (m_hTwainMutex!=NULL) { return TRUE; } _tcscpy(szMutexName,str_Mutex); hMutex=CreateMutex(NULL,FALSE,szMutexName); if (hMutex!=NULL) { error_code=GetLastError(); if (error_code==ERROR_ALREADY_EXISTS||error_code==ERROR_ACCESS_DENIED) { b_ret=CloseHandle(hMutex); hMutex=NULL; b_ret=TRUE; return b_ret; } else { CloseHandle(hMutex); b_ret=FALSE; return b_ret; } } else { return TRUE; } return b_ret; } BOOL CTwainMutex::CloseTwainMutex() { BOOL b_ret=FALSE; if (m_hTwainMutex!=NULL) { b_ret=CloseHandle(m_hTwainMutex); if (!b_ret) { MessageBox(NULL, TEXT("释放资源失败"), 0, MB_ICONWARNING); } m_hTwainMutex=NULL; return b_ret; } return TRUE; }