#include "atlimage.h"
HICON ToIcon(const std::wstring wstrFile, std::wstring wstrSaveFile = L"")
{
CImage img;
img.Load(wstrFile.c_str());//可以是jpg,png,gif格式图片
int w = img.GetWidth();
int h = img.GetHeight();
int cx = w;
int cy = h;
CDC * dc = CDC::FromHandle(GetWindowDC(GetDesktopWindow()));
CDC mdc;
mdc.CreateCompatibleDC(dc);
CBitmap bmp;
bmp.CreateCompatibleBitmap(dc, cx, cy);
HBITMAP hOldBmp = (HBITMAP)mdc.SelectObject(bmp);
img.StretchBlt(mdc.m_hDC, 0, 0, cx, cy, 0, 0, w, h, SRCCOPY);
HBITMAP hBmp = (HBITMAP)bmp.m_hObject;
ICONINFO iconinfo;
memset(&iconinfo, 0, sizeof(iconinfo));
iconinfo.fIcon = 1;
iconinfo.hbmColor = hBmp;
iconinfo.hbmMask = hBmp;
iconinfo.xHotspot = 0;
iconinfo.yHotspot = 0;
HICON hIcon = CreateIconIndirect(&iconinfo);//获取HICON
/*if(hIcon)
{
dc->DrawIcon(0,0,hIcon);
}*/
img.Detach();
PICTDESC pictdesc;
memset(&pictdesc, 0, sizeof(pictdesc));
pictdesc.cbSizeofstruct = sizeof(pictdesc);
pictdesc.picType = PICTYPE_ICON;
pictdesc.icon.hicon = hIcon;
IPicture * pPic = NULL;
int ret = OleCreatePictureIndirect(&pictdesc, IID_IPicture, 1, (LPVOID*)&pPic);
LPSTREAM pStream = 0;
CreateStreamOnHGlobal(0, TRUE, &pStream);
LONG size = 0;
pPic->SaveAsFile(pStream, TRUE, &size);
//这步非常重要
///
LARGE_INTEGER li;
li.HighPart = 0;
li.LowPart = 0;
ULARGE_INTEGER ulnewpos;
pStream->Seek(li, STREAM_SEEK_SET, &ulnewpos);
///
if(!wstrSaveFile.empty()){
if (PathFileExistsW(wstrSaveFile.c_str()))
::DeleteFile(wstrSaveFile.c_str());
HANDLE hFile = CreateFile(wstrSaveFile.c_str(), GENERIC_ALL, 0, 0, CREATE_ALWAYS, 0, 0);//生成ico文件
if (hFile)
{
char* buf = new char[size];
memset(buf, 0, size);
ULONG nRead = 0;
pStream->Read(buf, size, &nRead);
ULONG nWrited = 0;
WriteFile(hFile, buf, nRead, &nWrited, 0);
CloseHandle(hFile);
delete[]buf;
}
}
return hIcon;
}
void SetWindowIcon(HWND hWnd, std::wstring wstrFile)
{
HICON hIcon = ToIcon(wstrFile.c_str());
::SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
::SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
::SendMessage(::GetWindow(hWnd, GW_OWNER), WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
::SendMessage(::GetWindow(hWnd, GW_OWNER), WM_SETICON, ICON_BIG, (LPARAM)hIcon);
}
// 直接ico文件更方便,如下即可
std::wstring pszFileName = L"C:\\Users\\r187\\Desktop\\logo.ico";
//这个函数在使用过程中发现不能用来加载png,而ico文件可以直接用
HICON hIcon = (HICON)::LoadImage(NULL, pszFileName.c_str(), IMAGE_ICON, 0, 0, 0x00000010);
::SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
::SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
::SendMessage(::GetWindow(hWnd, GW_OWNER), WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
::SendMessage(::GetWindow(hWnd, GW_OWNER), WM_SETICON, ICON_BIG, (LPARAM)hIcon);