#include <Windows.h>
#include <iostream>
const int X=200;
const int Y=50;
const int WIDTH=800;
const int HEIGHT=600;
const std::string szClassTitle="透明窗口";
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{
//定义窗口WNDCLASS类结构
WNDCLASS winclass={CS_HREDRAW|CS_VREDRAW,WndProc,0,0,hInstance,LoadIcon(NULL,IDI_APPLICATION),
LoadCursor(NULL,IDC_ARROW),(HBRUSH)GetStockObject(WHITE_BRUSH),NULL,szClassTitle.c_str()};
//注册窗口
if(!RegisterClass(&winclass))
return false;
//创建窗口
HWND hWnd=CreateWindow(szClassTitle.c_str(),szClassTitle.c_str(),WS_OVERLAPPEDWINDOW,X,Y,WIDTH,HEIGHT,
NULL,NULL,winclass.hInstance,NULL);
if(0==hWnd)
return 0;
//显示及更新窗口
ShowWindow(hWnd,SW_SHOWDEFAULT);
UpdateWindow(hWnd);
//设置WS_EX_LAYERED标志
long nRet=GetWindowLong(hWnd,GWL_EXSTYLE);
nRet=nRet|WS_EX_LAYERED;
SetWindowLong(hWnd,GWL_EXSTYLE,nRet);
//消息循环
MSG msg;
ZeroMemory(&msg,sizeof(MSG));
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam)
{
static HDC hdc,mdc;
static HBITMAP bg;
PAINTSTRUCT ps;
switch(message)
{
case WM_CREATE:
{
hdc=GetDC(hWnd);
mdc=CreateCompatibleDC(hdc);
bg=(HBITMAP)LoadImage(NULL,"bg.bmp",IMAGE_BITMAP,0,0,LR_LOADFROMFILE);
}
break;
//贴上背景图
case WM_PAINT:
{
hdc=BeginPaint(hWnd,&ps);
SelectObject(mdc,bg);
BitBlt(hdc,0,0,WIDTH,HEIGHT,mdc,0,0,SRCCOPY);
EndPaint(hWnd,&ps);
}
break;
//按下左键,窗口透明
case WM_LBUTTONDOWN:
{
MessageBeep(0);
SetLayeredWindowAttributes(hWnd,0,150,LWA_ALPHA);
}
break;
//按下右键,窗口恢复
case WM_RBUTTONDOWN:
{
MessageBeep(0);
SetLayeredWindowAttributes(hWnd,0,255,LWA_ALPHA);
}
break;
//按下ESC键退出
case WM_KEYDOWN:
{
if(wParam==VK_ESCAPE)
DestroyWindow(hWnd);
}
break;
case WM_DESTROY:
{
DeleteDC(mdc);
DeleteObject(bg);
ReleaseDC(hWnd,hdc);
PostQuitMessage(0);
}
break;
default:
return DefWindowProc(hWnd,message,wParam,lParam);
}
return 0;
}