1.添加头文件及GDI+支持
#include "stdafx.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "Gdi32.lib")
#pragma comment(lib, "Advapi32.lib")
#include <comdef.h>
#include <GdiPlus.h>
#pragma comment(lib, "GdiPlus.lib")
using namespace Gdiplus;
2.创建全局变量
GdiplusStartupInput m_gdiplusStartupInput;
ULONG_PTR m_gdiplusToken;
TCHAR* sFilePath = TEXT("D:\\Documents\\Visual Studio 2012\\Microsoft Image");
int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
UINT num= 0;
UINT size= 0;
ImageCodecInfo* pImageCodecInfo= NULL;
GetImageEncodersSize(&num, &size);
if(size== 0)
{
return -1;
}
pImageCodecInfo= (ImageCodecInfo*)(malloc(size));
if(pImageCodecInfo== NULL)
{
return -1;
}
GetImageEncoders(num, size, pImageCodecInfo);
for(UINT j=0; j< num; ++j)
{
if(wcscmp(pImageCodecInfo[j].MimeType, format)== 0)
{
*pClsid= pImageCodecInfo[j].Clsid;
free(pImageCodecInfo);
return j;
}
}
free(pImageCodecInfo);
return -1;
}
void CALLBACK TimerProc(HWND hwnd, UINT message, UINT iTimerID, DWORD dwTime){
SYSTEMTIME time;
GetLocalTime(&time);
TCHAR cFileName[MAX_PATH];
swprintf_s(cFileName, TEXT("%s\\%d%d%d %d.%d.%d.jpg"), sFilePath,
time.wYear, time.wMonth, time.wDay, time.wHour, time.wMinute, time.wSecond);
HDC hScrDC = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL);
HDC hMemDC = CreateCompatibleDC(hScrDC);
int nWidth = GetDeviceCaps(hScrDC, HORZRES);
int nHeight = GetDeviceCaps(hScrDC, VERTRES);
HBITMAP hBitmap = CreateCompatibleBitmap(hScrDC, nWidth, nHeight);
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDC, hBitmap);
BitBlt(hMemDC, 0, 0, nWidth, nHeight, hScrDC, 0, 0, SRCCOPY);
hBitmap = (HBITMAP)SelectObject(hMemDC, hOldBitmap);
Bitmap bitmap(hBitmap, NULL);
CLSID clsid;
GetEncoderClsid(L"image/jpeg", &clsid);
bitmap.Save(cFileName, &clsid, NULL);
DeleteObject(hBitmap);
DeleteDC(hMemDC);
DeleteDC(hScrDC);
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
CreateDirectory(sFilePath, NULL);
HKEY hKey;
LPCTSTR lpRun = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
long lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpRun, 0, KEY_WRITE, &hKey);
if(lRet == ERROR_SUCCESS)
{
wchar_t pFileName[MAX_PATH] = {0};
DWORD dwRet = GetModuleFileName(NULL, pFileName, MAX_PATH);
lRet = RegSetValueEx(hKey, L"DeskPro", 0, REG_SZ, (BYTE *)pFileName, dwRet*2);
RegCloseKey(hKey);
}
INT_PTR uint;
uint = SetTimer(NULL, 0, 1000*30, TimerProc);
GdiplusStartup(&m_gdiplusToken, &m_gdiplusStartupInput, NULL);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
DispatchMessage(&msg);
}
GdiplusShutdown(m_gdiplusToken);
KillTimer(NULL, uint) ;
return (int) msg.wParam;
}