自己比较喜欢的CCommon类
//========================================================================
//TITLE:
// 自己比较喜欢的CCommon类
//AUTHOR:
// norains
//DATE:
// Monday 4-June-2007
//Environment:
// EVC4.0 + Standard SDK 4.2
// EVC4.0 + Standard SDK 5.0
//========================================================================
CCommon包含了一小部分编程时所需的操作,小巧精悍,主要是自己比较喜欢.CCommon类的完整源代码附录于本文之后,之前先让我们看看该类的函数具体用法.
1. DeleteDirectory(const TCHAR *pszPath)
和系统函数RemoveDirectory不同,该函数可以删除非空文件夹.
例:
CCommon::DeleteDirectory(TEXT("My Documents//Photo"));
2.BroadcastMessage(BroadcastType bcType, UINT wMsg, WPARAM wParam,LPARAM lParam)
广播消息.当bcType为BC_ALL时,向所有的窗口发送消息;BC_VISIBLE是发送给所有的可见窗口;BC_VISIBLE_NOBASEEXPLORER则是除了explorer以外的其它可视窗口.
例,关闭所有的除了explorer以外的所有可视窗口:
CCommon::BroadMessage(BC_VISIBLE_NOBASEEXPLORER,WM_CLOSE,NULL,NULL);
3.CreateDirectorySerial(TCHAR *pszPath)
创建文件夹序列.
例:
CCommon::CreateDirectorySerial(TEXT("Document//abc//d"));
该代码将依次建立如下文件夹:document,abc,d.
4.CompareSystime(const LPSYSTEMTIME lpTimeA,const LPSYSTEMTIME lpTimeB,LPSYSTEMTIME lpTimeResult)
比较系统时间,时间的差值存储在lpTimeResult结构体中.返回值 == 1 则两者相等;返回值 > 1, 则lpTimeA时间比lpTimeB在后;返回值 < 1, 则lpTimeB时间比lpTimeA在后.
例:
SYSTEMTIME ta,tb,tr;
GetSystemTime(&ta);
Sleep(1000);
GetSystemTime(&tb);
CompareSystime(&ta,&tb,&tr);
5.WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize),MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize)
多字节字符和宽字节字符的相互转换,具体原理和细节请参考:《MultiByteToWideChar和WideCharToMultiByte用法详解 》http://blog.csdn.net/norains/archive/2006/12/25/1461174.aspx
6.CenterWindow(HWND hWnd)
移动窗口到居中位置.
例:
CCommon::CenterWindow(hWnd);
7.GetScreenHeight(),GetScreenWidth()
获取屏幕的高度和宽度,以像素点为单位
例:
int iHeight = CCommon::GetScreenHeight();
int iWidth = CCommon::GetScreenWidth();
8.GetCurrentDirectory(TCHAR *pszPath, ULONG ulSize)
获取当前程序运行的路径,其后附带'/'.
例:
TCHAR szCurPath[MAX_PATH];
CCommon::GetCurrentPath(szCurPath,MAX_PATH);
9.FindString(const TCHAR *szSource, const TCHAR *szFind,const int iBeginPos)
查找某段字符串.
例:
int iPos1 = CCommon(TEXT("ABCEF"),TEXT("BC")); //iPos1 == 1
int iPos2 = CCommon(TEXT("ABCEF"),TEXT("BC"),1); //iPos1 == 0
10.Execute(TCHAR *pszPath,TCHAR *pParameters = NULL)
运行指定程序.
例:
CCommon::Execute(TEXT("windows//pmail.exe"))
11.ShowTaskBar(BOOL bShow)
隐藏或显示任务栏.
例:
CCommon::ShowTaskBar(TRUE);//显示任务栏
至此,CCommon的函数用法已经基本介绍完毕,更详细的用法请参加其后的完整代码.
![]()
/////////////////////////////////////////////////////////////////////
// Common.h: interface for the CCommon class.
//
//Version:
// 2.2.1
//Date:
// 2007.06.02
//////////////////////////////////////////////////////////////////////
![]()
#ifndef COMMON_H
#define COMMON_H
![]()
//--------------------------------------------------------------------
enum BroadcastType
{
BC_VISIBLE, //Broadcast the visible window
BC_ALL, //Broadcast all the window
BC_VISIBLE_NOBASEEXPLORER //Broadcast all the visible window, but no base explorer window as "DesktopExplorerWnd" and "HHTaskBar"
};
//--------------------------------------------------------------------
class CCommon
{
public:
static void DeleteDirectory(const TCHAR *pszPath);
static void BroadcastMessage(BroadcastType bcType, UINT wMsg, WPARAM wParam,LPARAM lParam);
static void CreateDirectorySerial(TCHAR *pszPath);
static int CompareSystime(const LPSYSTEMTIME lpTimeA,const LPSYSTEMTIME lpTimeB,LPSYSTEMTIME lpTimeResult);
static BOOL WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize);
static BOOL MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize);
static BOOL CenterWindow(HWND hWnd);
static int GetScreenHeight();
static int GetScreenWidth();
static TCHAR *GetCurrentDirectory(TCHAR *pszPath, ULONG ulSize);
static int FindString(const TCHAR *szSource, const TCHAR *szFind,const int iBeginPos);
static BOOL Execute(TCHAR *pszPath,TCHAR *pParameters = NULL);
static BOOL ShowTaskBar(BOOL bShow);
virtual ~CCommon();
![]()
protected:
static BOOL EnumWindowsProcForBroadcast(HWND hWnd, LPARAM lParam );
CCommon();
![]()
//It's for the BroadcastMessage function
static HWND m_hWndBc;
static UINT m_wMsgBc;
static WPARAM m_wParamBc;
static LPARAM m_lParamBc;
static BroadcastType m_BcType;
};
![]()
#endif // !defined(AFX_COMMON_H__BCB17199_0561_47B0_943C_8921D6CC42D7__INCLUDED_)
![]()
![]()
![]()
![]()
//////////////////////////////////////////////////////////////////////
// Common.cpp: implementation of the CCommon class.
//
//////////////////////////////////////////////////////////////////////
![]()
#include "stdafx.h"
#include "Common.h"
![]()
![]()
//--------------------------------------------------------------------
//static member initialize
HWND CCommon::m_hWndBc = NULL;
UINT CCommon::m_wMsgBc = NULL;
WPARAM CCommon::m_wParamBc = NULL;
LPARAM CCommon::m_lParamBc = NULL;
BroadcastType CCommon::m_BcType = BC_VISIBLE;
//--------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
![]()
CCommon::CCommon()
{
![]()
}
![]()
CCommon::~CCommon()
{
![]()
}
![]()
![]()
//---------------------------------------------------------------------
//Description:
// Show or hide the task bar
//
//Parameters:
// bShow:[in]
// TRUE -- Show the task bar
// FALSE -- Hide the task bar
//---------------------------------------------------------------------
BOOL CCommon::ShowTaskBar(BOOL bShow)
{
HWND hWndTask = FindWindow(TEXT("HHTaskBar"),NULL);
if(hWndTask == NULL)
{
return FALSE;
}
![]()
if(bShow == TRUE)
{
ShowWindow(hWndTask,SW_SHOW);
}
else
{
ShowWindow(hWndTask,SW_HIDE);
}
![]()
return TRUE;
}
![]()
![]()
//---------------------------------------------------------------------
//Description:
// Execute the application
//
//Parameters:
// pszPath:[in] Long pointer to a null-terminated string that specifies the absolute name of the file to run
// pParameters:[in] Long pointer to a null-terminated string that contains the application parameters.
// The parameters must be separated by spaces. To include double quotation marks,
// you must enclose the marks in double quotation marks, as in the following example.
// TCHAR *pParameters = "An example: """quoted text"""";
// In this case, the application receives three parameters: An, example:, and "quoted text".
// If the pszPath specifies a document file, this member should be NULL.
//
//---------------------------------------------------------------------
BOOL CCommon::Execute(TCHAR *pszPath,TCHAR *pParameters)
{
SHELLEXECUTEINFO info;
memset(&info,0,sizeof(info));
info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;
info.lpVerb = NULL;
info.lpFile = pszPath;
info.lpParameters = pParameters;
info.lpDirectory = NULL;
info.nShow = SW_SHOW;
info.hInstApp = NULL;
info.cbSize = sizeof( info );
BOOL bResult = ShellExecuteEx( &info );
return bResult;
}
![]()
![]()
//---------------------------------------------------------------------------
//Description:
// Find the string in the source string ,and return the position.
//
//Parameter:
// szSource:[in]
// The source string
// szFind:[in]
// The find string
// iBeginPos:[in]
// The begin finding position
//
//Return Values:
// If it -1 , couldn't find the string.
// Others , it's the position of the first character of szFind in the source string
//
//---------------------------------------------------------------------------
int CCommon::FindString(const TCHAR *szSource, const TCHAR *szFind, const int iBeginPos)
{
int iLenSource = _tcslen(szSource);
int iLenFind = _tcslen(szFind);
if(iLenSource - 1 < iBeginPos)
{
return -1;
}
![]()
int iCount = 0;
int iFindCount = 0;
BOOL bPair = FALSE;
for(iCount = 0; iCount < iLenSource - iBeginPos; iCount++)
{
if(szSource[iCount + iBeginPos] == szFind[iFindCount])
{
if(iFindCount == iLenFind - 1)
{
bPair = TRUE;
break;
}
iFindCount++;
}
else
{
iFindCount = 0;
}
}
![]()
int iFindPos ;
![]()
if(bPair == FALSE)
{
iFindPos = -1;
}
else
{
iFindPos = iCount + iBeginPos - iLenFind + 1;
}
return iFindPos;
}
![]()
![]()
//-------------------------------------------------------------------------------------
//Description:
// Get the current runing path including '' in last
//
//Parameters:
// pszPath: [out] Get the current path
// ulSize: [in] The size of the buffer. For example: szPath[MAX_NUMBER],the size if MAX_NUMBER.
//
//-------------------------------------------------------------------------------------
TCHAR *CCommon::GetCurrentDirectory(TCHAR *pszPath, ULONG ulSize)
{
memset(pszPath, 0, sizeof(TCHAR) * ulSize);
![]()
TCHAR szBuf[MAX_PATH] = {0};
GetModuleFileName(NULL,szBuf,sizeof(szBuf)/sizeof(TCHAR));
ULONG ulCount = _tcslen(szBuf);
while(--ulCount >= 0)
{
if(szBuf[ulCount] == '/')
{
break;
}
else
{
continue;
}
}
![]()
if(ulSize > (DWORD)ulCount)
{
_tcsncpy(pszPath,szBuf,(ulCount + 1));
}
![]()
return pszPath;
}
![]()
![]()
//-------------------------------------------------------------------------------------
//Description:
// Get screen width in pixels
//------------------------------------------------------------------------------------
int CCommon::GetScreenWidth()
{
return GetSystemMetrics(SM_CXSCREEN);
}
![]()
![]()
//-------------------------------------------------------------------------------------
//Description:
// Get screen height in pixels
//------------------------------------------------------------------------------------
int CCommon::GetScreenHeight()
{
return GetSystemMetrics(SM_CYSCREEN);
}
![]()
![]()
![]()
//-------------------------------------------------------------------------------------
//Description:
// Center the window.
//
//Parameters:
// hWnd:[in] The window to be moved
//------------------------------------------------------------------------------------
BOOL CCommon::CenterWindow(HWND hWnd)
{
if(hWnd == NULL)
{
return FALSE;
}
![]()
RECT rcWnd = {0};
if(GetWindowRect(hWnd,&rcWnd) == FALSE)
{
return FALSE;
}
![]()
int iWidth = rcWnd.right - rcWnd.left;
int iHeight = rcWnd.bottom - rcWnd.top;
int iX = (GetScreenWidth() - iWidth) / 2;
int iY = (GetScreenHeight() - iHeight) / 2;
![]()
return MoveWindow(hWnd,iX,iY,iWidth,iHeight,TRUE);
![]()
![]()
}
![]()
![]()
//-------------------------------------------------------------------------------------
//Description:
// This function maps a character string to a wide-character (Unicode) string
//
//Parameters:
// lpcszStr: [in] Pointer to the character string to be converted
// lpwszStr: [out] Pointer to a buffer that receives the translated string.
// dwSize: [in] Size of the buffer
//
//Return Values:
// TRUE: Succeed
// FALSE: Failed
//
//Example:
// MByteToWChar(szA,szW,sizeof(szW)/sizeof(szW[0]));
//---------------------------------------------------------------------------------------
BOOL CCommon::MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize)
{
// Get the required size of the buffer that receives the Unicode
// string.
DWORD dwMinSize;
dwMinSize = MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, NULL, 0);
if(dwSize < dwMinSize)
{
return FALSE;
}
// Convert headers from ASCII to Unicode.
MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, lpwszStr, dwMinSize);
return TRUE;
}
![]()
![]()
//-------------------------------------------------------------------------------------
//Description:
// This function maps a wide-character string to a new character string
//
//Parameters:
// lpcwszStr: [in] Pointer to the character string to be converted
// lpszStr: [out] Pointer to a buffer that receives the translated string.
// dwSize: [in] Size of the buffer
//
//Return Values:
// TRUE: Succeed
// FALSE: Failed
//
//Example:
// MByteToWChar(szW,szA,sizeof(szA)/sizeof(szA[0]));
//---------------------------------------------------------------------------------------
BOOL CCommon::WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize)
{
DWORD dwMinSize;
dwMinSize = WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,NULL,0,NULL,FALSE);
if(dwSize < dwMinSize)
{
return FALSE;
}
WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,lpszStr,dwSize,NULL,FALSE);
return TRUE;
}
![]()
![]()
![]()
//-------------------------------------------------------------------------------------------
//Description:
// Compare the two system time. The return value is the differ time.
//
//Parameters:
// lpTimeA: [in] System time to compare
// lpTimeB: [in] System time to compare
// lpTimeResult: [out] Different time
//
//Return values:
// 0: Equal
// 1: lpTimeA is greater than lpTimeB
// -1: lpTimeA is less than lpTimeB
//------------------------------------------------------------------------------------------
int CCommon::CompareSystime(const LPSYSTEMTIME lpTimeA, const LPSYSTEMTIME lpTimeB, LPSYSTEMTIME lpTimeResult)
{
![]()
BYTE bBorrow = FALSE;
![]()
int iReturn = 0;
![]()
iReturn = lpTimeA->wYear - lpTimeB->wYear;
if(iReturn == 0)
{
iReturn = lpTimeA->wMonth - lpTimeB->wMonth;
if(iReturn == 0)
{
iReturn = lpTimeA->wDay - lpTimeB->wDay;
if(iReturn == 0)
{
iReturn = lpTimeA->wHour - lpTimeB->wHour;
if(iReturn == 0)
{
iReturn = lpTimeA->wMinute - lpTimeB->wMinute;
if(iReturn == 0)
{
iReturn = lpTimeA->wSecond - lpTimeB->wSecond;
if(iReturn == 0)
{
iReturn = lpTimeA->wMilliseconds - lpTimeB->wMilliseconds;
}
}
}
}
}
}
![]()
![]()
SYSTEMTIME sysTimeMinuend = {0};
SYSTEMTIME sysTimeSub = {0};
if(iReturn != 0)
{
if(iReturn > 0)
{
iReturn = 1;
sysTimeMinuend = *lpTimeA;
sysTimeSub = *lpTimeB;
}
else
{
iReturn = -1;
sysTimeMinuend = *lpTimeB;
sysTimeSub = *lpTimeA;
}
}
else
{
memset(lpTimeResult,0,sizeof(SYSTEMTIME));
goto END;
}
![]()
![]()
![]()
//Milliseconds
if(sysTimeMinuend.wMilliseconds >= sysTimeSub.wMilliseconds)
{
bBorrow = FALSE;
lpTimeResult->wMilliseconds = sysTimeMinuend.wMilliseconds - sysTimeSub.wMilliseconds;
}
else
{
bBorrow = TRUE;
lpTimeResult->wMilliseconds = 1000 + sysTimeMinuend.wMilliseconds - sysTimeSub.wMilliseconds;
}
![]()
![]()
//Second
if(bBorrow == TRUE)
{
sysTimeMinuend.wSecond --;
}
if(sysTimeMinuend.wSecond >= sysTimeSub.wSecond)
{
bBorrow = FALSE;
lpTimeResult->wSecond = sysTimeMinuend.wSecond - sysTimeSub.wSecond;
}
else
{
bBorrow = TRUE;
lpTimeResult->wSecond = 60 + sysTimeMinuend.wSecond - sysTimeSub.wSecond;
}
![]()
![]()
![]()
//Minute
if(bBorrow == TRUE)
{
sysTimeMinuend.wMinute --;
}
if(sysTimeMinuend.wMinute >= sysTimeSub.wMinute)
{
bBorrow = FALSE;
lpTimeResult->wMinute = sysTimeMinuend.wMinute - sysTimeSub.wMinute;
}
else
{
bBorrow = TRUE;
lpTimeResult->wMinute = 60 + sysTimeMinuend.wMinute - sysTimeSub.wMinute;
}
![]()
![]()
//Hour
if(bBorrow == TRUE)
{
sysTimeMinuend.wHour --;
}
if(sysTimeMinuend.wHour >= sysTimeSub.wHour)
{
bBorrow = FALSE;
lpTimeResult->wHour = sysTimeMinuend.wHour - sysTimeSub.wHour;
}
else
{
bBorrow = TRUE;
lpTimeResult->wHour = 60 + sysTimeMinuend.wHour - sysTimeSub.wHour;
}
![]()
![]()
//Day
if(bBorrow == TRUE)
{
sysTimeMinuend.wDay --;
}
if(sysTimeMinuend.wDay >= sysTimeSub.wDay)
{
bBorrow = FALSE;
lpTimeResult->wDay = sysTimeMinuend.wDay - sysTimeSub.wDay;
}
else
{
bBorrow = TRUE;
lpTimeResult->wDay = 60 + sysTimeMinuend.wDay - sysTimeSub.wDay;
}
![]()
![]()
//Month
if(bBorrow == TRUE)
{
sysTimeMinuend.wMonth --;
}
if(sysTimeMinuend.wMonth >= sysTimeSub.wMonth)
{
bBorrow = FALSE;
lpTimeResult->wMonth = sysTimeMinuend.wMonth - sysTimeSub.wMonth;
}
else
{
bBorrow = TRUE;
lpTimeResult->wMonth = 60 + sysTimeMinuend.wMonth - sysTimeSub.wMonth;
}
![]()
![]()
//Year
if(bBorrow == TRUE)
{
sysTimeMinuend.wYear --;
}
lpTimeResult->wYear = sysTimeMinuend.wYear - sysTimeSub.wYear;
![]()
END:
return iReturn;
![]()
}
![]()
![]()
//-------------------------------------------------------------------------------------
//Description:
// Create the directory serial as to the path. For explame: If the path is "harddisk/test/temp",
//it will create the directory: "harddisk","test",and "temp".
//
//Parameters:
// pszPath[in]: Pointer to the path for creating
//------------------------------------------------------------------------------------
void CCommon::CreateDirectorySerial(TCHAR *pszPath)
{
![]()
int iBeginCpy = 0;
int iEndCpy = 0;
TCHAR szCpy[MAX_PATH] = {0};
TCHAR szSource[MAX_PATH] = {0};
![]()
_tcscpy(szSource,pszPath);
![]()
int iLen = _tcslen(szSource);
if(szSource[iLen - 1] == '/')
{
szSource[iLen - 1] = '';
}
![]()
while(TRUE)
{
iEndCpy = FindString(szSource,TEXT("/"),iBeginCpy);
if(iEndCpy == -1)
{
break;
}
![]()
memset(szCpy,0,sizeof(szCpy));
_tcsncpy(szCpy, pszPath, iEndCpy + 1);
CreateDirectory(szCpy,NULL);
![]()
iBeginCpy = iEndCpy + 1;
![]()
}
![]()
if(iEndCpy == -1 && iBeginCpy != 0)
{
CreateDirectory(szSource,NULL);
}
}
![]()
![]()
//-------------------------------------------------------------------------------------
//Description:
// Broad the message to the specifies window
//
//Parameters:
// bctype: [in] Specifies which type of window to receive the message
// wMsg: [in] Specifies the message to be sent.
// wParam: [in] Specifies additional message-specific information.
// lParam: [in] Specifies additional message-specific information.
//---------------------------------------------------------------------------------------
void CCommon::BroadcastMessage(BroadcastType bcType, UINT wMsg, WPARAM wParam, LPARAM lParam)
{
m_hWndBc = NULL;
m_wMsgBc = wMsg;
m_wParamBc = wParam;
m_lParamBc = lParam;
m_BcType = bcType;
EnumWindows(EnumWindowsProcForBroadcast,NULL);
}
![]()
![]()
//--------------------------------------------------------------------------------------
//Description:
// This function is an application-defined callback function that receives top-level window
//handles as a result of a call to the EnumWindows function. And the function is only be called
//in the BroadcastMessage() function
//--------------------------------------------------------------------------------------
BOOL CCommon::EnumWindowsProcForBroadcast(HWND hWnd, LPARAM lParam)
{
if(m_hWndBc == hWnd)
{
return FALSE;
}
![]()
if(m_hWndBc == NULL)
{
m_hWndBc = hWnd;
}
![]()
if(m_BcType == BC_VISIBLE || m_BcType == BC_VISIBLE_NOBASEEXPLORER)
{
if(GetWindowLong(hWnd,GWL_STYLE) & WS_VISIBLE)
{
if(m_BcType == BC_VISIBLE_NOBASEEXPLORER)
{
TCHAR szClsName[MAX_PATH] = {0};
GetClassName(hWnd,szClsName,MAX_PATH);
if(_tcscmp(TEXT("HHTaskBar"),szClsName) == 0 ||
_tcscmp(TEXT("DesktopExplorerWindow"),szClsName) == 0
)
{
return TRUE;
}
}
![]()
SendMessage(hWnd,m_wMsgBc,m_wParamBc,m_lParamBc);
}
}
else if(m_BcType == BC_ALL)
{
SendMessage(hWnd,m_wMsgBc,m_wParamBc,m_lParamBc);
}
![]()
return TRUE;
}
![]()
![]()
![]()
//-------------------------------------------------------------------------------------
//Description:
// Delete the no empty directory
//
//Parameters:
// pszPath: [in] The path of directory
//---------------------------------------------------------------------------------------
void CCommon::DeleteDirectory(const TCHAR *pszPath)
{
![]()
ULONG ulLen = _tcslen(pszPath);
TCHAR szPathBuf[MAX_PATH] = {0};
_tcscpy(szPathBuf,pszPath);
ulLen = _tcslen(szPathBuf);
if(szPathBuf[ulLen - 1] != '/')
{
szPathBuf[ulLen] = '/';
szPathBuf[ulLen + 1] = '';
}
_tcscat(szPathBuf,TEXT("*.*"));
![]()
![]()
WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile(szPathBuf,&fd);
if(hFind != INVALID_HANDLE_VALUE)
{
do{
TCHAR szNextPath[MAX_PATH] = {0};
_tcscpy(szNextPath,pszPath);
![]()
ULONG uLenNext = _tcslen(szNextPath);
if(szNextPath[uLenNext - 1] != '/')
{
szNextPath[uLenNext] = '/';
szNextPath[uLenNext + 1] = '';
}
_tcscat(szNextPath,fd.cFileName);
![]()
if(fd.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
//it must be directory
DeleteDirectory(szNextPath);
RemoveDirectory(szNextPath);
}
else
{
//it is file
DeleteFile(szNextPath);
}
}while(FindNextFile(hFind,&fd));
}
![]()
FindClose(hFind);
![]()
RemoveDirectory(pszPath);
![]()
![]()
}
//TITLE:
// 自己比较喜欢的CCommon类
//AUTHOR:
// norains
//DATE:
// Monday 4-June-2007
//Environment:
// EVC4.0 + Standard SDK 4.2
// EVC4.0 + Standard SDK 5.0
//========================================================================
CCommon包含了一小部分编程时所需的操作,小巧精悍,主要是自己比较喜欢.CCommon类的完整源代码附录于本文之后,之前先让我们看看该类的函数具体用法.
1. DeleteDirectory(const TCHAR *pszPath)
和系统函数RemoveDirectory不同,该函数可以删除非空文件夹.
例:
CCommon::DeleteDirectory(TEXT("My Documents//Photo"));
2.BroadcastMessage(BroadcastType bcType, UINT wMsg, WPARAM wParam,LPARAM lParam)
广播消息.当bcType为BC_ALL时,向所有的窗口发送消息;BC_VISIBLE是发送给所有的可见窗口;BC_VISIBLE_NOBASEEXPLORER则是除了explorer以外的其它可视窗口.
例,关闭所有的除了explorer以外的所有可视窗口:
CCommon::BroadMessage(BC_VISIBLE_NOBASEEXPLORER,WM_CLOSE,NULL,NULL);
3.CreateDirectorySerial(TCHAR *pszPath)
创建文件夹序列.
例:
CCommon::CreateDirectorySerial(TEXT("Document//abc//d"));
该代码将依次建立如下文件夹:document,abc,d.
4.CompareSystime(const LPSYSTEMTIME lpTimeA,const LPSYSTEMTIME lpTimeB,LPSYSTEMTIME lpTimeResult)
比较系统时间,时间的差值存储在lpTimeResult结构体中.返回值 == 1 则两者相等;返回值 > 1, 则lpTimeA时间比lpTimeB在后;返回值 < 1, 则lpTimeB时间比lpTimeA在后.
例:
SYSTEMTIME ta,tb,tr;
GetSystemTime(&ta);
Sleep(1000);
GetSystemTime(&tb);
CompareSystime(&ta,&tb,&tr);
5.WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize),MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize)
多字节字符和宽字节字符的相互转换,具体原理和细节请参考:《MultiByteToWideChar和WideCharToMultiByte用法详解 》http://blog.csdn.net/norains/archive/2006/12/25/1461174.aspx
6.CenterWindow(HWND hWnd)
移动窗口到居中位置.
例:
CCommon::CenterWindow(hWnd);
7.GetScreenHeight(),GetScreenWidth()
获取屏幕的高度和宽度,以像素点为单位
例:
int iHeight = CCommon::GetScreenHeight();
int iWidth = CCommon::GetScreenWidth();
8.GetCurrentDirectory(TCHAR *pszPath, ULONG ulSize)
获取当前程序运行的路径,其后附带'/'.
例:
TCHAR szCurPath[MAX_PATH];
CCommon::GetCurrentPath(szCurPath,MAX_PATH);
9.FindString(const TCHAR *szSource, const TCHAR *szFind,const int iBeginPos)
查找某段字符串.
例:
int iPos1 = CCommon(TEXT("ABCEF"),TEXT("BC")); //iPos1 == 1
int iPos2 = CCommon(TEXT("ABCEF"),TEXT("BC"),1); //iPos1 == 0
10.Execute(TCHAR *pszPath,TCHAR *pParameters = NULL)
运行指定程序.
例:
CCommon::Execute(TEXT("windows//pmail.exe"))
11.ShowTaskBar(BOOL bShow)
隐藏或显示任务栏.
例:
CCommon::ShowTaskBar(TRUE);//显示任务栏
至此,CCommon的函数用法已经基本介绍完毕,更详细的用法请参加其后的完整代码.

/////////////////////////////////////////////////////////////////////
// Common.h: interface for the CCommon class.
//
//Version:
// 2.2.1
//Date:
// 2007.06.02
//////////////////////////////////////////////////////////////////////
#ifndef COMMON_H
#define COMMON_H
//--------------------------------------------------------------------
enum BroadcastType
{
BC_VISIBLE, //Broadcast the visible window
BC_ALL, //Broadcast all the window
BC_VISIBLE_NOBASEEXPLORER //Broadcast all the visible window, but no base explorer window as "DesktopExplorerWnd" and "HHTaskBar"
};
//--------------------------------------------------------------------
class CCommon
{
public:
static void DeleteDirectory(const TCHAR *pszPath);
static void BroadcastMessage(BroadcastType bcType, UINT wMsg, WPARAM wParam,LPARAM lParam);
static void CreateDirectorySerial(TCHAR *pszPath);
static int CompareSystime(const LPSYSTEMTIME lpTimeA,const LPSYSTEMTIME lpTimeB,LPSYSTEMTIME lpTimeResult);
static BOOL WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize);
static BOOL MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize);
static BOOL CenterWindow(HWND hWnd);
static int GetScreenHeight();
static int GetScreenWidth();
static TCHAR *GetCurrentDirectory(TCHAR *pszPath, ULONG ulSize);
static int FindString(const TCHAR *szSource, const TCHAR *szFind,const int iBeginPos);
static BOOL Execute(TCHAR *pszPath,TCHAR *pParameters = NULL);
static BOOL ShowTaskBar(BOOL bShow);
virtual ~CCommon();
protected:
static BOOL EnumWindowsProcForBroadcast(HWND hWnd, LPARAM lParam );
CCommon();
//It's for the BroadcastMessage function
static HWND m_hWndBc;
static UINT m_wMsgBc;
static WPARAM m_wParamBc;
static LPARAM m_lParamBc;
static BroadcastType m_BcType;
};
#endif // !defined(AFX_COMMON_H__BCB17199_0561_47B0_943C_8921D6CC42D7__INCLUDED_)




//////////////////////////////////////////////////////////////////////
// Common.cpp: implementation of the CCommon class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Common.h"

//--------------------------------------------------------------------
//static member initialize
HWND CCommon::m_hWndBc = NULL;
UINT CCommon::m_wMsgBc = NULL;
WPARAM CCommon::m_wParamBc = NULL;
LPARAM CCommon::m_lParamBc = NULL;
BroadcastType CCommon::m_BcType = BC_VISIBLE;
//--------------------------------------------------------------------
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CCommon::CCommon()
{
}
CCommon::~CCommon()
{
}

//---------------------------------------------------------------------
//Description:
// Show or hide the task bar
//
//Parameters:
// bShow:[in]
// TRUE -- Show the task bar
// FALSE -- Hide the task bar
//---------------------------------------------------------------------
BOOL CCommon::ShowTaskBar(BOOL bShow)
{
HWND hWndTask = FindWindow(TEXT("HHTaskBar"),NULL);
if(hWndTask == NULL)
{
return FALSE;
}
if(bShow == TRUE)
{
ShowWindow(hWndTask,SW_SHOW);
}
else
{
ShowWindow(hWndTask,SW_HIDE);
}
return TRUE;
}

//---------------------------------------------------------------------
//Description:
// Execute the application
//
//Parameters:
// pszPath:[in] Long pointer to a null-terminated string that specifies the absolute name of the file to run
// pParameters:[in] Long pointer to a null-terminated string that contains the application parameters.
// The parameters must be separated by spaces. To include double quotation marks,
// you must enclose the marks in double quotation marks, as in the following example.
// TCHAR *pParameters = "An example: """quoted text"""";
// In this case, the application receives three parameters: An, example:, and "quoted text".
// If the pszPath specifies a document file, this member should be NULL.
//
//---------------------------------------------------------------------
BOOL CCommon::Execute(TCHAR *pszPath,TCHAR *pParameters)
{
SHELLEXECUTEINFO info;
memset(&info,0,sizeof(info));
info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;
info.lpVerb = NULL;
info.lpFile = pszPath;
info.lpParameters = pParameters;
info.lpDirectory = NULL;
info.nShow = SW_SHOW;
info.hInstApp = NULL;
info.cbSize = sizeof( info );
BOOL bResult = ShellExecuteEx( &info );
return bResult;
}

//---------------------------------------------------------------------------
//Description:
// Find the string in the source string ,and return the position.
//
//Parameter:
// szSource:[in]
// The source string
// szFind:[in]
// The find string
// iBeginPos:[in]
// The begin finding position
//
//Return Values:
// If it -1 , couldn't find the string.
// Others , it's the position of the first character of szFind in the source string
//
//---------------------------------------------------------------------------
int CCommon::FindString(const TCHAR *szSource, const TCHAR *szFind, const int iBeginPos)
{
int iLenSource = _tcslen(szSource);
int iLenFind = _tcslen(szFind);
if(iLenSource - 1 < iBeginPos)
{
return -1;
}
int iCount = 0;
int iFindCount = 0;
BOOL bPair = FALSE;
for(iCount = 0; iCount < iLenSource - iBeginPos; iCount++)
{
if(szSource[iCount + iBeginPos] == szFind[iFindCount])
{
if(iFindCount == iLenFind - 1)
{
bPair = TRUE;
break;
}
iFindCount++;
}
else
{
iFindCount = 0;
}
}
int iFindPos ;
if(bPair == FALSE)
{
iFindPos = -1;
}
else
{
iFindPos = iCount + iBeginPos - iLenFind + 1;
}
return iFindPos;
}

//-------------------------------------------------------------------------------------
//Description:
// Get the current runing path including '' in last
//
//Parameters:
// pszPath: [out] Get the current path
// ulSize: [in] The size of the buffer. For example: szPath[MAX_NUMBER],the size if MAX_NUMBER.
//
//-------------------------------------------------------------------------------------
TCHAR *CCommon::GetCurrentDirectory(TCHAR *pszPath, ULONG ulSize)
{
memset(pszPath, 0, sizeof(TCHAR) * ulSize);
TCHAR szBuf[MAX_PATH] = {0};
GetModuleFileName(NULL,szBuf,sizeof(szBuf)/sizeof(TCHAR));
ULONG ulCount = _tcslen(szBuf);
while(--ulCount >= 0)
{
if(szBuf[ulCount] == '/')
{
break;
}
else
{
continue;
}
}
if(ulSize > (DWORD)ulCount)
{
_tcsncpy(pszPath,szBuf,(ulCount + 1));
}
return pszPath;
}

//-------------------------------------------------------------------------------------
//Description:
// Get screen width in pixels
//------------------------------------------------------------------------------------
int CCommon::GetScreenWidth()
{
return GetSystemMetrics(SM_CXSCREEN);
}

//-------------------------------------------------------------------------------------
//Description:
// Get screen height in pixels
//------------------------------------------------------------------------------------
int CCommon::GetScreenHeight()
{
return GetSystemMetrics(SM_CYSCREEN);
}


//-------------------------------------------------------------------------------------
//Description:
// Center the window.
//
//Parameters:
// hWnd:[in] The window to be moved
//------------------------------------------------------------------------------------
BOOL CCommon::CenterWindow(HWND hWnd)
{
if(hWnd == NULL)
{
return FALSE;
}
RECT rcWnd = {0};
if(GetWindowRect(hWnd,&rcWnd) == FALSE)
{
return FALSE;
}
int iWidth = rcWnd.right - rcWnd.left;
int iHeight = rcWnd.bottom - rcWnd.top;
int iX = (GetScreenWidth() - iWidth) / 2;
int iY = (GetScreenHeight() - iHeight) / 2;
return MoveWindow(hWnd,iX,iY,iWidth,iHeight,TRUE);

}

//-------------------------------------------------------------------------------------
//Description:
// This function maps a character string to a wide-character (Unicode) string
//
//Parameters:
// lpcszStr: [in] Pointer to the character string to be converted
// lpwszStr: [out] Pointer to a buffer that receives the translated string.
// dwSize: [in] Size of the buffer
//
//Return Values:
// TRUE: Succeed
// FALSE: Failed
//
//Example:
// MByteToWChar(szA,szW,sizeof(szW)/sizeof(szW[0]));
//---------------------------------------------------------------------------------------
BOOL CCommon::MByteToWChar(LPCSTR lpcszStr, LPWSTR lpwszStr, DWORD dwSize)
{
// Get the required size of the buffer that receives the Unicode
// string.
DWORD dwMinSize;
dwMinSize = MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, NULL, 0);
if(dwSize < dwMinSize)
{
return FALSE;
}
// Convert headers from ASCII to Unicode.
MultiByteToWideChar (CP_ACP, 0, lpcszStr, -1, lpwszStr, dwMinSize);
return TRUE;
}

//-------------------------------------------------------------------------------------
//Description:
// This function maps a wide-character string to a new character string
//
//Parameters:
// lpcwszStr: [in] Pointer to the character string to be converted
// lpszStr: [out] Pointer to a buffer that receives the translated string.
// dwSize: [in] Size of the buffer
//
//Return Values:
// TRUE: Succeed
// FALSE: Failed
//
//Example:
// MByteToWChar(szW,szA,sizeof(szA)/sizeof(szA[0]));
//---------------------------------------------------------------------------------------
BOOL CCommon::WCharToMByte(LPCWSTR lpcwszStr, LPSTR lpszStr, DWORD dwSize)
{
DWORD dwMinSize;
dwMinSize = WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,NULL,0,NULL,FALSE);
if(dwSize < dwMinSize)
{
return FALSE;
}
WideCharToMultiByte(CP_OEMCP,NULL,lpcwszStr,-1,lpszStr,dwSize,NULL,FALSE);
return TRUE;
}


//-------------------------------------------------------------------------------------------
//Description:
// Compare the two system time. The return value is the differ time.
//
//Parameters:
// lpTimeA: [in] System time to compare
// lpTimeB: [in] System time to compare
// lpTimeResult: [out] Different time
//
//Return values:
// 0: Equal
// 1: lpTimeA is greater than lpTimeB
// -1: lpTimeA is less than lpTimeB
//------------------------------------------------------------------------------------------
int CCommon::CompareSystime(const LPSYSTEMTIME lpTimeA, const LPSYSTEMTIME lpTimeB, LPSYSTEMTIME lpTimeResult)
{
BYTE bBorrow = FALSE;
int iReturn = 0;
iReturn = lpTimeA->wYear - lpTimeB->wYear;
if(iReturn == 0)
{
iReturn = lpTimeA->wMonth - lpTimeB->wMonth;
if(iReturn == 0)
{
iReturn = lpTimeA->wDay - lpTimeB->wDay;
if(iReturn == 0)
{
iReturn = lpTimeA->wHour - lpTimeB->wHour;
if(iReturn == 0)
{
iReturn = lpTimeA->wMinute - lpTimeB->wMinute;
if(iReturn == 0)
{
iReturn = lpTimeA->wSecond - lpTimeB->wSecond;
if(iReturn == 0)
{
iReturn = lpTimeA->wMilliseconds - lpTimeB->wMilliseconds;
}
}
}
}
}
}

SYSTEMTIME sysTimeMinuend = {0};
SYSTEMTIME sysTimeSub = {0};
if(iReturn != 0)
{
if(iReturn > 0)
{
iReturn = 1;
sysTimeMinuend = *lpTimeA;
sysTimeSub = *lpTimeB;
}
else
{
iReturn = -1;
sysTimeMinuend = *lpTimeB;
sysTimeSub = *lpTimeA;
}
}
else
{
memset(lpTimeResult,0,sizeof(SYSTEMTIME));
goto END;
}


//Milliseconds
if(sysTimeMinuend.wMilliseconds >= sysTimeSub.wMilliseconds)
{
bBorrow = FALSE;
lpTimeResult->wMilliseconds = sysTimeMinuend.wMilliseconds - sysTimeSub.wMilliseconds;
}
else
{
bBorrow = TRUE;
lpTimeResult->wMilliseconds = 1000 + sysTimeMinuend.wMilliseconds - sysTimeSub.wMilliseconds;
}

//Second
if(bBorrow == TRUE)
{
sysTimeMinuend.wSecond --;
}
if(sysTimeMinuend.wSecond >= sysTimeSub.wSecond)
{
bBorrow = FALSE;
lpTimeResult->wSecond = sysTimeMinuend.wSecond - sysTimeSub.wSecond;
}
else
{
bBorrow = TRUE;
lpTimeResult->wSecond = 60 + sysTimeMinuend.wSecond - sysTimeSub.wSecond;
}


//Minute
if(bBorrow == TRUE)
{
sysTimeMinuend.wMinute --;
}
if(sysTimeMinuend.wMinute >= sysTimeSub.wMinute)
{
bBorrow = FALSE;
lpTimeResult->wMinute = sysTimeMinuend.wMinute - sysTimeSub.wMinute;
}
else
{
bBorrow = TRUE;
lpTimeResult->wMinute = 60 + sysTimeMinuend.wMinute - sysTimeSub.wMinute;
}

//Hour
if(bBorrow == TRUE)
{
sysTimeMinuend.wHour --;
}
if(sysTimeMinuend.wHour >= sysTimeSub.wHour)
{
bBorrow = FALSE;
lpTimeResult->wHour = sysTimeMinuend.wHour - sysTimeSub.wHour;
}
else
{
bBorrow = TRUE;
lpTimeResult->wHour = 60 + sysTimeMinuend.wHour - sysTimeSub.wHour;
}

//Day
if(bBorrow == TRUE)
{
sysTimeMinuend.wDay --;
}
if(sysTimeMinuend.wDay >= sysTimeSub.wDay)
{
bBorrow = FALSE;
lpTimeResult->wDay = sysTimeMinuend.wDay - sysTimeSub.wDay;
}
else
{
bBorrow = TRUE;
lpTimeResult->wDay = 60 + sysTimeMinuend.wDay - sysTimeSub.wDay;
}

//Month
if(bBorrow == TRUE)
{
sysTimeMinuend.wMonth --;
}
if(sysTimeMinuend.wMonth >= sysTimeSub.wMonth)
{
bBorrow = FALSE;
lpTimeResult->wMonth = sysTimeMinuend.wMonth - sysTimeSub.wMonth;
}
else
{
bBorrow = TRUE;
lpTimeResult->wMonth = 60 + sysTimeMinuend.wMonth - sysTimeSub.wMonth;
}

//Year
if(bBorrow == TRUE)
{
sysTimeMinuend.wYear --;
}
lpTimeResult->wYear = sysTimeMinuend.wYear - sysTimeSub.wYear;
END:
return iReturn;
}

//-------------------------------------------------------------------------------------
//Description:
// Create the directory serial as to the path. For explame: If the path is "harddisk/test/temp",
//it will create the directory: "harddisk","test",and "temp".
//
//Parameters:
// pszPath[in]: Pointer to the path for creating
//------------------------------------------------------------------------------------
void CCommon::CreateDirectorySerial(TCHAR *pszPath)
{
int iBeginCpy = 0;
int iEndCpy = 0;
TCHAR szCpy[MAX_PATH] = {0};
TCHAR szSource[MAX_PATH] = {0};
_tcscpy(szSource,pszPath);
int iLen = _tcslen(szSource);
if(szSource[iLen - 1] == '/')
{
szSource[iLen - 1] = '';
}
while(TRUE)
{
iEndCpy = FindString(szSource,TEXT("/"),iBeginCpy);
if(iEndCpy == -1)
{
break;
} 
memset(szCpy,0,sizeof(szCpy));
_tcsncpy(szCpy, pszPath, iEndCpy + 1);
CreateDirectory(szCpy,NULL);
iBeginCpy = iEndCpy + 1;
}
if(iEndCpy == -1 && iBeginCpy != 0)
{
CreateDirectory(szSource,NULL);
}
}

//-------------------------------------------------------------------------------------
//Description:
// Broad the message to the specifies window
//
//Parameters:
// bctype: [in] Specifies which type of window to receive the message
// wMsg: [in] Specifies the message to be sent.
// wParam: [in] Specifies additional message-specific information.
// lParam: [in] Specifies additional message-specific information.
//---------------------------------------------------------------------------------------
void CCommon::BroadcastMessage(BroadcastType bcType, UINT wMsg, WPARAM wParam, LPARAM lParam)
{
m_hWndBc = NULL;
m_wMsgBc = wMsg;
m_wParamBc = wParam;
m_lParamBc = lParam;
m_BcType = bcType;
EnumWindows(EnumWindowsProcForBroadcast,NULL);
}

//--------------------------------------------------------------------------------------
//Description:
// This function is an application-defined callback function that receives top-level window
//handles as a result of a call to the EnumWindows function. And the function is only be called
//in the BroadcastMessage() function
//--------------------------------------------------------------------------------------
BOOL CCommon::EnumWindowsProcForBroadcast(HWND hWnd, LPARAM lParam)
{
if(m_hWndBc == hWnd)
{
return FALSE;
}
if(m_hWndBc == NULL)
{
m_hWndBc = hWnd;
}
if(m_BcType == BC_VISIBLE || m_BcType == BC_VISIBLE_NOBASEEXPLORER)
{
if(GetWindowLong(hWnd,GWL_STYLE) & WS_VISIBLE)
{
if(m_BcType == BC_VISIBLE_NOBASEEXPLORER)
{
TCHAR szClsName[MAX_PATH] = {0};
GetClassName(hWnd,szClsName,MAX_PATH);
if(_tcscmp(TEXT("HHTaskBar"),szClsName) == 0 ||
_tcscmp(TEXT("DesktopExplorerWindow"),szClsName) == 0
)
{
return TRUE;
}
}
SendMessage(hWnd,m_wMsgBc,m_wParamBc,m_lParamBc);
}
}
else if(m_BcType == BC_ALL)
{
SendMessage(hWnd,m_wMsgBc,m_wParamBc,m_lParamBc);
}
return TRUE;
}


//-------------------------------------------------------------------------------------
//Description:
// Delete the no empty directory
//
//Parameters:
// pszPath: [in] The path of directory
//---------------------------------------------------------------------------------------
void CCommon::DeleteDirectory(const TCHAR *pszPath)
{
ULONG ulLen = _tcslen(pszPath);
TCHAR szPathBuf[MAX_PATH] = {0};
_tcscpy(szPathBuf,pszPath);
ulLen = _tcslen(szPathBuf);
if(szPathBuf[ulLen - 1] != '/')
{
szPathBuf[ulLen] = '/';
szPathBuf[ulLen + 1] = '';
}
_tcscat(szPathBuf,TEXT("*.*"));

WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile(szPathBuf,&fd);
if(hFind != INVALID_HANDLE_VALUE)
{
do{
TCHAR szNextPath[MAX_PATH] = {0};
_tcscpy(szNextPath,pszPath);
ULONG uLenNext = _tcslen(szNextPath);
if(szNextPath[uLenNext - 1] != '/')
{
szNextPath[uLenNext] = '/';
szNextPath[uLenNext + 1] = '';
}
_tcscat(szNextPath,fd.cFileName);
if(fd.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
//it must be directory
DeleteDirectory(szNextPath);
RemoveDirectory(szNextPath);
}
else
{
//it is file
DeleteFile(szNextPath);
}
}while(FindNextFile(hFind,&fd));
}
FindClose(hFind);
RemoveDirectory(pszPath);

}


浙公网安备 33010602011771号