常用的宏定义 |
说明,这些宏可能在下面的函数中用到,如果要想直接反这些函数拷来用的话,一定要正确定义这些宏(这些宏定义也要一起拷贝)
下面这些函数都很独立,也就是说,你直接把这个函数拷到你的代码中,就可以用,前提是你要把一些头文件及我定义的宏加上。
1,根据文件路径提取其ICON
2,根据文件路径提取其Thumbnail
3,根据路径提取ICON,返回HICON
4,创建快捷方式
5,保存图片到文件(PNG)
// Define the macro to release com object
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(p) if ((p) != NULL) { (p)->Release(); (p) = NULL;}
#endif
// Safe delete pointer
#ifndef SAFE_DELETE
#define SAFE_DELETE(p) if ((p) != NULL) { delete (p); (p) = NULL; }
#endif
// Get the low bit of a word
#ifndef WORD_LO
#define WORD_LO(x) ((byte)((WORD)(x) & 255) )
#endif
// Get the high bit of a word
#ifndef WORD_HI
#define WORD_HI(x) ((byte)((WORD)(x) >> 8) )
#endif
// Convert a letter from lower case to upper case
#ifndef UPCASE
#define UPCASE(c) (((c)>='a' &&(c)<='z') ? ((c)-0x20) : (c) )
#endif
1,根据文件路径提取其ICON
//
HBITMAPCommonHelper::ExtractFileIcon(LPCTSTR pszPath, UINT nWidth, UINTnHeight)
{
HBITMAPhBitmpa = NULL;
if ( (NULL!= pszPath) && (nWidth> 0.0) && (nHeight> 0.0) )
{
IShellItemImageFactory *psif = NULL;
SIZE size = { nWidth, nHeight };
// +1 psif
HRESULT hr = ::SHCreateItemFromParsingName(pszPath, NULL,IID_PPV_ARGS(&psif));
if (SUCCEEDED(hr) && (NULL !=psif))
{
psif->GetImage(size, SIIGBF_ICONONLY,&hBitmpa);
// -1 psif
SAFE_RELEASE(psif);
}
}
return hBitmpa;
}
2,根据文件路径提取其Thumbnail
//
HBITMAPCommonHelper::ExtractFileThumbnail(LPCTSTR pszPath, UINT nWidth,UINT nHeight)
{
HBITMAPhBitmpa = NULL;
if ( (NULL!= pszPath) && (nWidth> 0.0) && (nHeight> 0.0) )
{
IShellItemImageFactory *psif = NULL;
SIZE size = { nWidth, nHeight };
// +1 psif
HRESULT hr = ::SHCreateItemFromParsingName(pszPath, NULL,IID_PPV_ARGS(&psif));
if (SUCCEEDED(hr) && (NULL !=psif))
{
psif->GetImage(size, SIIGBF_THUMBNAILONLY,&hBitmpa);
// -1 psif
SAFE_RELEASE(psif);
}
}
return hBitmpa;
}
3,根据路径提取ICON,返回HICON
//
HICON CommonHelper::GetIcon(IN LPCTSTR lpszfilePath)
{
// Get filename and directory
if ((lpszfilePath == NULL) || (0 == wcslen(lpszfilePath)) )
{
return NULL;
}
if (FALSE== PathFileExists(lpszfilePath))
{
return NULL;
}
WCHAR*pDir =NULL; // The folder path
WCHAR *pFile=NULL; // The file name
HICON hIcon=NULL; // The icon handler
IExtractIcon*piextractIcon = NULL; // The pointer to IExtractIcon to extracticon
IShellFolder*pshdesktop =NULL; // Thepointer to desktop shell folder
IShellFolder*pshworkdir =NULL; // Thepointer to work directory shell folder
LPITEMIDLISTpidworkDir =NULL; // The pidl of work directory
LPITEMIDLISTpidworkfile =NULL; // Thepidl of file
HRESULT hr =S_OK;
FPStringstr(lpszfilePath);
int nPos =str.find_last_of('\\');
if (nPos ==-1)
{
return NULL;
}
FPStringstrDir(str.substr(0, nPos));
FPStringstrFile(str.substr(nPos + 1, str.length()));
pDir =const_cast
pFile =const_cast
// +1pshdesktop Retrieves the IShellFolder interface for the desktopfolder.
if (FAILED(SHGetDesktopFolder(&pshdesktop)) )
{
return NULL;
}
// +2pidworkDir Translates the display name of a file object or a folderinto an item identifier list
if (FAILED(pshdesktop->ParseDisplayName(NULL, NULL,pDir, NULL, &pidworkDir, NULL)) )
{
goto Clearup;
}
// +3pshworkdir Get work directory shell folder pointer by workdirectory pidl
if (FAILED(pshdesktop->BindToObject(pidworkDir, NULL,IID_IShellFolder, (LPVOID*)&pshworkdir)) )
{
goto Clearup;
}
// +4pidworkfile Get the work directory file pidl pointed by thepFile.
if (FAILED(pshworkdir->ParseDisplayName(NULL, NULL,pFile, NULL, &pidworkfile, NULL)) )
{
goto Clearup;
}
// +5piextractIcon Get pointer to IExtractIcon by pidl
if(SUCCEEDED(pshworkdir->GetUIObjectOf(NULL, 1,(LPCITEMIDLIST*)&pidworkfile, IID_IExtractIcon,NULL, (LPVOID*)&piextractIcon)))
{
int uIndex = 0;
WCHAR szIconLocation[MAX_PATH] = {0};
UINT dwFlags = IEIFLAG_ASPECT;
if (SUCCEEDED(piextractIcon->GetIconLocation(GIL_FORSHELL,szIconLocation, MAX_PATH, &uIndex,&dwFlags)) )
{
HICON hsmallIcon = NULL;
DWORD dwsize = 0x100;
hr = piextractIcon->Extract(szIconLocation, uIndex,&hIcon, &hsmallIcon, dwsize);
if ( hIcon == NULL )
{
dwsize = 0x20;
piextractIcon->Extract(szIconLocation, uIndex,&hIcon, NULL, dwsize);
}
}
}
Clearup:
// -5piextractIcon
SAFE_RELEASE(piextractIcon);
// -4pidworkDir
CoTaskMemFree(pidworkfile);
// -3pshworkdir
SAFE_RELEASE(pshworkdir);
// -2pidworkDir
CoTaskMemFree(pidworkDir);
// -1pshdesktop
SAFE_RELEASE(pshdesktop);
returnhIcon;
}
4,创建快捷方式
//
HRESULT CommonHelper::CreateShortcut(LPCTSTR pszlinkPath,LPCTSTR psztargetPath)
{
HRESULT hr =-1;
if ( (NULL!= pszlinkPath) && (NULL !=psztargetPath) )
{
IShellLink *psl = NULL;
IPersistFile *ppf = NULL;
CoInitialize(NULL);
// +1 psl
HRESULT hr = CoCreateInstance(CLSID_ShellLink,
NULL,
CLSCTX_INPROC_SERVER,
IID_IShellLink,
reinterpret_cast
if ( SUCCEEDED(hr) &&SUCCEEDED(psl->SetPath(psztargetPath)) )
{
// +2 ppf
hr = psl->QueryInterface(IID_IPersistFile,reinterpret_cast
if (SUCCEEDED(hr) && (NULL !=ppf))
{
hr = ppf->Save(pszlinkPath, TRUE);
}
}
// -2 ppf
SAFE_RELEASE(ppf);
// -1 psl
SAFE_RELEASE(psl);
CoUninitialize();
}
returnhr;
}
5,保存图片到文件(PNG)
//
HRESULT CommonHelper::SaveImage(LPCTSTR pszfilePath, HBITMAPhbitmap)
{
HRESULT hr =-1;
if (NULL ==pszfilePath)
{
return hr;
}
Colorcolor;
// +1pbitmap
Bitmap*pbitmap = Gdiplus::Bitmap::FromHBITMAP(hbitmap, NULL);
if ( NULL ==pbitmap )
{
return hr;
}
// Thefirst parameter of GetEncoderClsid should be these values asfollow
CLSIDclsid;
if(GetEncoderClsid(_T("image/png"), &clsid))
{
if (pbitmap->Save(pszfilePath,&clsid, NULL) == Gdiplus::Ok)
{
hr = S_OK;
}
}
// -1pbitmap
SAFE_DELETE(pbitmap);
returnhr;
}
函数可能会用到的数据结构及枚举定义如下
enum BUTTON_STATE
{
BUTTON_NORMAL = 0,
BUTTON_HOVER = 1,
BUTTON_PRESSED = 2,
BUTTON_DISABLED = 3,
};
typedef struct _SHNOTIFY
{
LPITEMIDLISTm_Item1;
LPITEMIDLISTm_Item2;
} SHNOTIFY, *LPSHNOTIFY;
typedef struct _SHORTCUTINFO
{
LPTSTRpLinkPath;
LPTSTRpTargetPath;
LPTSTRpDescription;
LPTSTRpArgument;
WORDwHotkey;
}SHORTCUTINFO, *LPSHORTCUTINFO;
typedef struct _ASSOCAPPINFO
{
LPWSTRpFileName;
LPWSTRpUIName;
BOOLisRecommanded;
}ASSOCAPPINFO, *LPASSOCAPPINFO;
typedef struct _KNOWNITEM
{
LPTSTRFilePath;
LPTSTRDisplayName;
HICON Icon;
_KNOWNITEM()
{
FilePath = NULL;
DisplayName = NULL;
Icon = NULL;
}
~_KNOWNITEM()
{
SAFE_DELETE(FilePath);
SAFE_DELETE(DisplayName);
DestroyIcon(Icon);
}
}KNOWNITEM, *LPKNOWNITEM;
typedef struct _FILEINFO
{
TCHARcFilePath[MAX_PATH];
TCHARcFileName[MAX_PATH];
TCHARcTypeName[80];
FILETIMEftCreateTime;
FILETIMEftLastAccessTime;
FILETIMEftLastWriteTime;
DWORDdwFileAttributes;
DWORDnFileSizeHigh;
DWORDnFileSizeLow;
HICONhIcon;
HBITMAPhThumbnailBitmap;
_FILEINFO()
{
ZeroMemory(&cFilePath, MAX_PATH *sizeof(TCHAR));
ZeroMemory(&cFileName, MAX_PATH *sizeof(TCHAR));
ZeroMemory(&cTypeName, 80 * sizeof(TCHAR));
dwFileAttributes = 0;
nFileSizeHigh = 0;
nFileSizeLow = 0;
hIcon = NULL;
hThumbnailBitmap = NULL;
}
~_FILEINFO()
{
DestroyIcon(hIcon);
DeleteObject(hThumbnailBitmap);
}
}FILEINFO, *LPFILEINFO;
#defineWM_MRUNOTIFY WM_USER + 1
#define WM_BUTTONCLICK WM_USER + 2
1,解析快捷方式
HRESULT CommonHelper::ResolveShortcut(IN WCHAR* plinkPath, OUTWCHAR* ptargetPath)
{
HRESULT hr =-1;
if ((plinkPath != NULL) && (ptargetPath!= NULL) )
{
IShellLink *psl = NULL;
IPersistFile *ppf = NULL;
CoInitialize(NULL);
// +1 psl
hr = CoCreateInstance(CLSID_ShellLink,
NULL,
CLSCTX_INPROC_SERVER,
IID_IShellLink,
reinterpret_cast
if ( SUCCEEDED(hr) && (psl != NULL))
{
// +2 ppf
hr = psl->QueryInterface(IID_IPersistFile,reinterpret_cast
if ( SUCCEEDED(hr) && (ppf != NULL))
{
if ( SUCCEEDED(ppf->Load(plinkPath, STGM_READ)))
{
if ( SUCCEEDED(psl->Resolve(NULL, SLR_NOUPDATE|SLR_NOSEARCH|SLR_NOTRACK|SLR_NO_UI|(0<< 16))) )
{
WIN32_FIND_DATA wfd;
hr = psl->GetPath(ptargetPath, MAX_PATH,&wfd, SLGP_RAWPATH);
}
}
}
}
// -2 ppf
SAFE_RELEASE(ppf);
// -1 psl
SAFE_RELEASE(psl);
CoUninitialize();
}
returnhr;
}
2,根据文件后缀得到其默认的打开方式(如.txt对应Notepad.exe)
//
HRESULT CommonHelper::GetDefaultAssocApp(IN LPCWSTRpszextension, OUT LPWSTR pszappPath)
{
HRESULT hr =-1;
if ((pszextension != NULL) &&(pszappPath != NULL) )
{
DWORD bufferSize = MAX_PATH + 1;
hr = AssocQueryString(ASSOCF_INIT_DEFAULTTOSTAR,
ASSOCSTR_EXECUTABLE,
pszextension,
NULL,
pszappPath,
&bufferSize);
}
returnhr;
}
3,根据文件后缀得到其关联的应用程序信息。如路径,描述(Notepad对应记事本)
//
HRESULT CommonHelper::FileAssocApplicationEx(IN LPCWSTRpszextension, OUT LPASSOCAPPINFO* assocAppInfo)
{
HRESULT hr =-1;
if ( NULL== assocAppInfo )
{
return hr;
}
CoInitialize(NULL);
IEnumAssocHandlers *penumAssocHandler = NULL;
IAssocHandler *passocHandler = NULL;
// +1penumAssocHandler
if (SUCCEEDED(SHAssocEnumHandlers(pszextension,ASSOC_FILTER_RECOMMENDED, &penumAssocHandler)))
{
ULONG fetched = 0;
// +2 passocHandler
hr = penumAssocHandler->Next(1,&passocHandler, &fetched);
if ( SUCCEEDED(hr) &&(passocHandler != NULL) )
{
*assocAppInfo = new ASSOCAPPINFO();
hr =passocHandler->GetName(&(*assocAppInfo)->pFileName);
hr =passocHandler->GetUIName(&(*assocAppInfo)->pUIName);
(*assocAppInfo)->isRecommanded =(passocHandler->IsRecommended() == S_OK) ? TRUE :FALSE;
}
}
// -2passocHandler
SAFE_RELEASE(passocHandler);
// -1penumAssocHandler
SAFE_RELEASE(penumAssocHandler);
CoUninitialize();
returnhr;
}
4,使窗体居中显示
//
BOOL CommonHelper::SetWindowCenter(HWND hwnd)
{
if (!IsWindow(hwnd) )
{
return FALSE;
}
// Getwindow width and height
RECTrect;
GetWindowRect(hwnd, &rect);
LONGlWndWidth = rect.right - rect.left;
LONGlWndHeight = rect.bottom - rect.top;
// Getmonitor information
MONITORINFOmi;
ZeroMemory(&mi, sizeof(MONITORINFO));
mi.cbSize =sizeof(MONITORINFO);
HWNDhParent = ::GetParent(hwnd);
if ((hParent != NULL) &&IsWindow(hParent) &&IsWindowVisible(hParent) )
{
// Get parent rect
RECT rectParent;
GetWindowRect(hParent, &rectParent);
mi.rcWork.top = rectParent.top;
mi.rcWork.bottom = rectParent.bottom;
mi.rcWork.left = rectParent.left;
mi.rcWork.right = rectParent.right;
}
else
{
GetMonitorInfo(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST),&mi);
}
LONGlLeft = ( mi.rcWork.right - mi.rcWork.left ) / 2 - lWndWidth /2;
LONG lTop =( mi.rcWork.bottom - mi.rcWork.top ) / 2 - lWndHeight / 2;
returnSetWindowPos(hwnd, HWND_TOP, lLeft, lTop, -1, -1, SWP_NOSIZE |SWP_NOZORDER);
}
5,给控件或窗体加ToolTip
//
BOOL CommonHelper::AddToolTip(HINSTANCE hInst, HWND htoolWnd,LPCTSTR pszToolTipText)
{
if ( NULL ==pszToolTipText )
{
return FALSE;
}
INITCOMMONCONTROLSEX initCtrls;
initCtrls.dwSize = sizeof(INITCOMMONCONTROLSEX);
initCtrls.dwICC = ICC_BAR_CLASSES | ICC_TAB_CLASSES |ICC_WIN95_CLASSES;
if (!InitCommonControlsEx(&initCtrls) )
{
return FALSE;
}
HWNDhParentWnd = GetParent(htoolWnd);
HWNDhwndToolTip = CreateWindowEx(WS_EX_TOPMOST,
TOOLTIPS_CLASS, //ToolTip
NULL,
WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
hParentWnd,
NULL,
hInst, NULL);
if ( NULL== hwndToolTip )
{
return FALSE;
}
SendMessage(hwndToolTip, TTM_ACTIVATE, TRUE, 0);
TOOLINFOtoolInfo;
toolInfo.cbSize = sizeof(TOOLINFO);
toolInfo.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
toolInfo.uId= (UINT_PTR)htoolWnd;
toolInfo.hwnd = hParentWnd;
toolInfo.hinst = hInst;
toolInfo.lpszText =const_cast
toolInfo.rect.left = toolInfo.rect.right = toolInfo.rect.bottom =toolInfo.rect.top = 0;
SendMessage(hwndToolTip, TTM_ADDTOOL, 0,(LPARAM)(LPTOOLINFO)&toolInfo);
returnTRUE;
}
6,显示Taskbar and StartMenu Properties对话框
//
void CommonHelper::ShowTrayPropertiesDialog()
{
CoInitialize(NULL);
IShellDispatchPtr shell("Shell.APplication");
// ShowTaskbar And Start Menu Properties Dialog box
shell->TrayProperties();
shell.Release();
CoUninitialize();
Sleep(500);
// Getthe tab control hwnd and set focus to a specified tabcontrol.
HWNDhDestopHwnd = ::GetDesktopWindow();
HWND hwnd =::FindWindowEx(hDestopHwnd, NULL, _T("#32770"), NULL);
HWNDhTabCtlHwnd = NULL;
while (hwnd!= NULL)
{
hTabCtlHwnd = ::FindWindowEx(hwnd, NULL, L"SysTabControl32",L"");
if (hTabCtlHwnd != NULL)
{
// Set the first tab selected. The third parameter is the index ofselected tab that you want.
::SendMessage(hTabCtlHwnd, TCM_SETCURFOCUS, 1, 0);
break;
}
hwnd = ::FindWindowEx(hDestopHwnd, hwnd, _T("#32770"), NULL);
}
}
7,判断当前用户是否是Admin
//
BOOL CommonHelper::IsUserAdmin()
{
BOOL isAdmin= FALSE;
PSID psid =NULL;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
BOOLbSuccess =AllocateAndInitializeSid(&NtAuthority, // A handle to an access token
2, // Specifies the number of subauthorities to place in the SID
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&psid);
if (TRUE ==bSuccess)
{
bSuccess = CheckTokenMembership(NULL, psid,&isAdmin);
isAdmin = (TRUE == bSuccess) ? isAdmin : FALSE;
FreeSid(psid);
}
returnisAdmin;
}
8,判断当前用户是否打开了UAC(Vista orWin7 OS)
//
BOOL CommonHelper::IsEnableUAC()
{
BOOLisEnableUAC = FALSE;
OSVERSIONINFO osversioninfo;
ZeroMemory(&osversioninfo,sizeof(osversioninfo));
osversioninfo.dwOSVersionInfoSize = sizeof(osversioninfo);
BOOLbSuccess = GetVersionEx(&osversioninfo);
if(bSuccess)
{
// window vista or windows server 2008 or later operatingsystem
if ( osversioninfo.dwMajorVersion > 5 )
{
HKEY hKEY = NULL;
DWORD dwType = REG_DWORD;
DWORD dwEnableLUA = 0;
DWORD dwSize = sizeof(DWORD);
LONG status = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\"),
0,
KEY_READ,
&hKEY);
if ( ERROR_SUCCESS == status )
{
status = RegQueryValueEx(hKEY,
TEXT("EnableLUA"),
NULL,
&dwType,
(BYTE*)&dwEnableLUA,
&dwSize);
if (ERROR_SUCCESS == status)
{
isEnableUAC = (dwEnableLUA == 1) ? TRUE : FALSE;
}
RegCloseKey(hKEY);
}
}
}
returnisEnableUAC;
}
9,得到一种图片(PNG、JPG.etc)格式的CLSID
//
BOOL CommonHelper::GetEncoderClsid(LPCTSTR pszformat, CLSID*pclsid)
{
BOOL bResult= FALSE;
UINTnumEncoders =0; // number of image decoders
UINT size =0; // size, in bytes, of the image decoder array
ImageCodecInfo* pImageCodecInfo = NULL;
// Howmany decoders are there?
// How big(in bytes) is the array of all ImageCodecInfo objects?
GetImageEncodersSize(&numEncoders,&size);
pImageCodecInfo = (ImageCodecInfo*)malloc(size);
if ( NULL ==pImageCodecInfo )
{
return FALSE;
}
Statusresult = GetImageEncoders(numEncoders, size,pImageCodecInfo);
if (result== Gdiplus::Ok)
{
for(UINT j = 0; j < numEncoders; ++j)
{
if( wcscmp(pImageCodecInfo[j].MimeType, pszformat) == 0 )
{
*pclsid = pImageCodecInfo[j].Clsid;
bResult = TRUE;
break;
}
}
}
free(pImageCodecInfo);
returnbResult;
}
10,得到当前系统时间,返回特定格式字符串
//
BOOL CommonHelper::GetCurrentSystemTime(OUT LPWSTRpszSystemTime)
{
FILETIMEfileTime;
SYSTEMTIMEsystemTime;
SYSTEMTIMElocalTime;
TIME_ZONE_INFORMATION tzinfo;
GetSystemTimeAsFileTime(&fileTime);
FileTimeToSystemTime(&fileTime,&systemTime);
GetTimeZoneInformation(&tzinfo);
BOOLbSuccess = SystemTimeToTzSpecificLocalTime(&tzinfo,&systemTime, &localTime);
if(bSuccess)
{
wsprintf(pszSystemTime, _T("%04d/%02d/%02d %02d:%02d:%02d"),
localTime.wYear, localTime.wMonth, localTime.wDay, localTime.wHour,localTime.wMinute, localTime.wSecond);
}
returnFALSE;
}
程序内我就没有写多少注释,相信大家都看得懂。
未完待续,大家多交流,相互学习。