TryTaskbar.cpp

// TryTaskbar.cpp : 定义应用程序的入口点。
//

#include "stdafx.h"
#include "TryTaskbar.h"

//至此,上面提到的所有功能都已实现。有几个头文件需要包含到程序中: 
#include <shobjidl.h> 
#include <dwmapi.h> 
#include <tchar.h> 
#include <strsafe.h> 
#include <GdiPlus.h> 
//编译时需要链接的库有:dwmapi.lib gdiplus.lib
#pragma comment(lib,"dwmapi.lib")
#pragma comment(lib,"gdiplus.lib")

#define MAX_LOADSTRING 100


UINT WM_TASKBARBUTTONCREATED;	//用户消息
ITaskbarList4 *g_pTaskbar;
HICON g_hRed, g_hGreen, g_hBlue;
HWND g_hWnd;
// 全局变量:
HINSTANCE hInst;								// 当前实例
TCHAR szTitle[MAX_LOADSTRING];					// 标题栏文本
TCHAR szWindowClass[MAX_LOADSTRING];			// 主窗口类名

// 此代码模块中包含的函数的前向声明:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK	About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

 	// TODO: 在此放置代码。
		//初始化GDI+
	ULONG_PTR token;
	Gdiplus::GdiplusStartupInput input;
	Gdiplus::GdiplusStartup(&token, &input, NULL);
	//加载图标资源
	g_hRed = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_RED));
	g_hGreen = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_GREEN));
	g_hBlue = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_BLUE));
	//注册用户消息
	//注册用户消息 
	WM_TASKBARBUTTONCREATED = :: RegisterWindowMessage (TEXT ("TaskbarButtonCreated" )); 


	MSG msg;
	HACCEL hAccelTable;

	// 初始化全局字符串
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_TRYTASKBAR, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// 执行应用程序初始化:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TRYTASKBAR));

	//设置窗口属性,打开自定义缩略图和AeroPeek预览
	BOOL truth = TRUE;
	DwmSetWindowAttribute(g_hWnd, DWMWA_HAS_ICONIC_BITMAP, &truth, sizeof(truth));
	DwmSetWindowAttribute(g_hWnd, DWMWA_FORCE_ICONIC_REPRESENTATION, &truth, sizeof(truth));

	// 主消息循环:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	//UnregisterClass(TEXT("ClsTestTaskbar"), GetModuleHandle(NULL));
	UnregisterClass(szWindowClass, GetModuleHandle(NULL));
	//关闭GDI+
	Gdiplus::GdiplusShutdown(token);

	return (int) msg.wParam;
}



//
//  函数: MyRegisterClass()
//
//  目的: 注册窗口类。
//
//  注释:
//
//    仅当希望
//    此代码与添加到 Windows 95 中的“RegisterClassEx”
//    函数之前的 Win32 系统兼容时,才需要此函数及其用法。调用此函数十分重要,
//    这样应用程序就可以获得关联的
//    “格式正确的”小图标。
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= LoadIcon(hInstance, MAKEINTRESOURCE(IDI_TRYTASKBAR));
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= MAKEINTRESOURCE(IDC_TRYTASKBAR);
	wcex.lpszClassName	= szWindowClass;
	wcex.hIconSm		= LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

	return RegisterClassEx(&wcex);
}

//
//   函数: InitInstance(HINSTANCE, int)
//
//   目的: 保存实例句柄并创建主窗口
//
//   注释:
//
//        在此函数中,我们在全局变量中保存实例句柄并
//        创建和显示主程序窗口。
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
   HWND &hWnd=g_hWnd;

   hInst = hInstance; // 将实例句柄存储在全局变量中

   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
      CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}


void AddThumbnailButtons() 
{
	if(g_pTaskbar == NULL) return;
	//buttons
	THUMBBUTTONMASK dwMask = THB_ICON | THB_TOOLTIP;
	THUMBBUTTON thbButtons[3];

	thbButtons[0].dwMask = dwMask;
	thbButtons[0].iId = 0;
	thbButtons[0].hIcon = g_hRed;
	StringCbCopy(thbButtons[0].szTip, sizeof(thbButtons[0].szTip), TEXT("Red"));

	thbButtons[1].dwMask = dwMask;
	thbButtons[1].iId = 1;
	thbButtons[1].hIcon = g_hGreen;
	StringCbCopy(thbButtons[1].szTip, sizeof(thbButtons[1].szTip), TEXT("Green"));

	thbButtons[2].dwMask = dwMask;
	thbButtons[2].iId = 2;
	thbButtons[2].hIcon = g_hBlue;
	StringCbCopy(thbButtons[2].szTip, sizeof(thbButtons[2].szTip), TEXT("Blue"));

	g_pTaskbar->ThumbBarAddButtons(g_hWnd, ARRAYSIZE(thbButtons), thbButtons);
}

void OnThumbnailButtonClicked( int id ) 
{
	switch(id)
	{
	case 0:
		SetForegroundWindow(g_hWnd);
		MessageBox(g_hWnd, TEXT("Red button clicked!"), NULL, MB_OK);
		break;
	case 1:
		SetForegroundWindow(g_hWnd);
		MessageBox(g_hWnd, TEXT("Green button clicked!"), NULL, MB_OK);
		break;
	case 2:
		SetForegroundWindow(g_hWnd);
		MessageBox(g_hWnd, TEXT("Blue button clicked!"), NULL, MB_OK);
		break;
	}
}
//将PNG等格式的资源加载为GdiPlus::Bitmap
Gdiplus::Bitmap *LoadBitmapFromResource( HMODULE hModule, UINT resID, LPCTSTR resType )
{
	//分配一块内存,把加载的资源拷贝到内存中
	//取得资源的句柄
	HRSRC hRsrc = FindResource(hModule, MAKEINTRESOURCE(resID), resType);
	if (hRsrc == NULL) 
	{
		return NULL;
	}
	//资源的大小
	int size = SizeofResource(GetModuleHandle(NULL), hRsrc);
	//加载资源
	HGLOBAL hGlobal = LoadResource(GetModuleHandle(NULL), hRsrc);
	if (hGlobal == NULL)
	{
		return NULL;
	}
	//分配相同大小的一块内存
	HGLOBAL hGlobal2 = GlobalAlloc(GMEM_MOVEABLE, size);
	if(hGlobal2 == NULL)
	{
		FreeResource(hGlobal);
		return NULL;
	}
	//锁资源
	LPVOID lpVoid = LockResource(hGlobal);
	if (lpVoid == NULL)
	{
		FreeResource(hGlobal);
		GlobalFree(hGlobal2);
		return NULL;
	}
	//锁内存
	LPVOID lpVoid2 = GlobalLock(hGlobal2);
	if (lpVoid2 == NULL)
	{
		UnlockResource(hGlobal);
		FreeResource(hGlobal);
		GlobalFree(hGlobal2);
		return NULL;
	}
	//将资源拷贝到内存
	memcpy(lpVoid2, lpVoid, size);
	//解锁
	GlobalUnlock(hGlobal2);
	UnlockResource(hGlobal);
	//创建流
	LPSTREAM lpStream;
	HRESULT hr = CreateStreamOnHGlobal(hGlobal2, TRUE, &lpStream);
	if (hr != S_OK)
	{
		FreeResource(hGlobal);
		GlobalFree(hGlobal2);
		return NULL;
	}
	//基于流创建GdiPlus::Bitmap
	Gdiplus::Bitmap *bmp = Gdiplus::Bitmap::FromStream(lpStream);
	//释放资源和内存
	FreeResource(hGlobal);
	GlobalFree(hGlobal2);
	return bmp;
}
//缩放GdiPlua::Bitmap
Gdiplus::Bitmap * ResizeBitmap( Gdiplus::Bitmap *bmpSrc, 
	int destWidth, int destHeight, bool keepAspect = true )
{
	//取得源图片宽度和高度
	int srcWidth = bmpSrc->GetWidth();
	int srcHeight = bmpSrc->GetHeight();
	//计算横向和纵向的缩放比率
	float scaleH = (float)destWidth / srcWidth;
	float scaleV = (float)destHeight / srcHeight;
	//如果需要保持长宽比,则横向和纵向统一采用较小的缩放比率
	if(keepAspect)
	{
		if (scaleH > scaleV)
		{
			scaleH = scaleV;
		}
		else
		{
			scaleV = scaleH;
		}
	}
	//计算目标宽高
	destWidth  = (int)(srcWidth * scaleH);
	destHeight = (int)(srcHeight * scaleV);
	//创建目标Bitmap
	Gdiplus::Bitmap *bmpDest = new Gdiplus::Bitmap(destWidth, destHeight, PixelFormat32bppARGB);
	Gdiplus::Graphics graphic(bmpDest);
	//设置插值算法
	graphic.SetInterpolationMode(Gdiplus::InterpolationModeHighQualityBicubic);
	//将源图像绘制到目标图像上
	graphic.DrawImage(bmpSrc, Gdiplus::Rect(0, 0, destWidth, destHeight), 
		0, 0, srcWidth, srcHeight, Gdiplus::UnitPixel);
	graphic.Flush();
	return bmpDest;
}

void OnSendThumbnail( HWND hWnd, int width, int height ) 
{
	//将资源加载为Bitmap
	Gdiplus::Bitmap *bmp = LoadBitmapFromResource(GetModuleHandle(NULL), IDB_THUMB, TEXT("PNG"));
	//缩放Bitmap
	Gdiplus::Bitmap *bmpResized = ResizeBitmap(bmp, width, height, true);
	//取得位图句柄
	HBITMAP hbmp;
	bmpResized->GetHBITMAP(UINT(Gdiplus::Color::AlphaMask), &hbmp); 
	//发送位图句柄
	DwmSetIconicThumbnail(hWnd, hbmp, 0);
	//释放对象
	DeleteObject(hbmp);
	delete bmpResized;
	delete bmp;
}

void OnSendPreview( HWND hWnd ) 
{
	//取得窗口客户区域
	RECT rcClient;
	GetClientRect(hWnd, &rcClient);
	//将资源加载为Bitmap
	Gdiplus::Bitmap *bmp = LoadBitmapFromResource(GetModuleHandle(NULL), IDB_PREVIEW, TEXT("PNG"));
	Gdiplus::Bitmap *bmpResized = ResizeBitmap(bmp, rcClient.right - rcClient.left,
		rcClient.bottom - rcClient.top, false);
	//取得位图句柄
	HBITMAP hbmp;
	bmpResized->GetHBITMAP(UINT(Gdiplus::Color::AlphaMask), &hbmp); 
	//发送位图句柄
	DwmSetIconicLivePreviewBitmap(hWnd, hbmp, NULL, 0);
	//释放对象
	DeleteObject(hbmp);
	delete bmpResized;
	delete bmp;
}


//
//  函数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  目的: 处理主窗口的消息。
//
//  WM_COMMAND	- 处理应用程序菜单
//  WM_PAINT	- 绘制主窗口
//  WM_DESTROY	- 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	//创建接口对象ITaskbarList
	if(message == WM_TASKBARBUTTONCREATED)
	{
		::CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&g_pTaskbar));
		g_pTaskbar->HrInit();
		g_pTaskbar->SetProgressState(g_hWnd, TBPF_ERROR);
		g_pTaskbar->SetProgressValue(g_hWnd, 50, 100);
		g_pTaskbar->SetOverlayIcon(g_hWnd, g_hRed, TEXT("Error"));
		g_pTaskbar->SetThumbnailTooltip(g_hWnd, TEXT("Some information"));
		AddThumbnailButtons();
	}

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		if (HIWORD(wParam) == THBN_CLICKED)
		{
			OnThumbnailButtonClicked(LOWORD(wParam));
		}
		else // 分析菜单选择:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}

		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: 在此添加任意绘图代码...
		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;

	case WM_DWMSENDICONICTHUMBNAIL:
		OnSendThumbnail(hWnd, HIWORD(lParam), LOWORD(lParam));
		break;
	case WM_DWMSENDICONICLIVEPREVIEWBITMAP:
		OnSendPreview(hWnd);
		break;

	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}

// “关于”框的消息处理程序。
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	UNREFERENCED_PARAMETER(lParam);
	switch (message)
	{
	case WM_INITDIALOG:
		return (INT_PTR)TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return (INT_PTR)TRUE;
		}
		break;
	}
	return (INT_PTR)FALSE;
}

你可能感兴趣的:(TryTaskbar.cpp)