Screen Killer —— 我的C++“屏幕保护程序”

来源:互联网 发布:淘宝助手怎么用 编辑:程序博客网 时间:2024/05/01 19:09

0.简介

      早前学C++Win32编程,了解了一点创建窗口的知识,就想写个屏幕保护程序什么的。。。


1.成品

       结果是写成了这个Screen Killer:大概就是以屏幕大小画矩形(也就是传说中的全屏),其中用随机函数生成不同的颜色,每100毫秒更新一次。效果自己想像吧。



2.源代码

//WinMain.cpp#include<Windows.h>#include<ctime>//to get a random seed#include<stdlib.h>//to set the random color of screen#define ID_TIMER 101LRESULT CALLBACK WindowProc(  __in  HWND hWnd,  __in  UINT uMsg,  __in  WPARAM wParam,  __in  LPARAM lParam);int APIENTRY WinMain( HINSTANCE hInstance,      HINSTANCE hPrevInstance,  LPSTR lpCmdLine,  int nCmdShow){srand( time(0) );LPCWSTR lpClassName = TEXT("tobeScreenKiller");LPCWSTR lpWindowName = TEXT("Screen Killer");WNDCLASS wc;wc.cbClsExtra = 0;wc.cbWndExtra = 0;wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);wc.hCursor = LoadCursor(NULL, IDI_QUESTION);wc.hIcon = LoadIcon(NULL, IDI_SHIELD);wc.hInstance = hInstance;wc.lpfnWndProc = WindowProc;wc.lpszClassName = lpClassName;wc.lpszMenuName = NULL;wc.style = CS_HREDRAW | CS_VREDRAW;RegisterClass(&wc);HWND hWnd;hWnd = CreateWindow(lpClassName, lpClassName, WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);ShowWindow(hWnd, SW_SHOWMAXIMIZED);UpdateWindow(hWnd);MSG msg;while( GetMessage(&msg, NULL, 0 , 0) ){TranslateMessage(&msg);DispatchMessage(&msg);}return msg.wParam;}LRESULT CALLBACK WindowProc(  __in  HWND hWnd,  __in  UINT uMsg,  __in  WPARAM wParam,  __in  LPARAM lParam){HDC hDC;RECT rect;PAINTSTRUCT ps;switch(uMsg){case WM_CREATE:{SetTimer(hWnd, ID_TIMER, 100, NULL);}break;case WM_TIMER:{InvalidateRect(hWnd, NULL, TRUE);//just refresh the window}break;case WM_PAINT:{hDC = BeginPaint(hWnd, &ps);GetClientRect(hWnd, &rect);//get all the screen to paintHBRUSH hBrush = CreateSolidBrush( RGB(rand()%256,rand()%256,rand()%256) );//create the random color to paintHBRUSH hOldBrush = (HBRUSH)SelectObject(hDC, hBrush);ShowCursor(FALSE);//hide the cursorFillRect(hDC, &rect, hBrush);//paint all the screen with a randomly colorful brushSelectObject(hDC, hOldBrush);DeleteObject(hBrush);//release the resourceEndPaint(hWnd, &ps);}break;case WM_CHAR://allow pressing any button to exit {if( VK_ESCAPE & wParam ){//MessageBeep( MB_ICONASTERISK );DestroyWindow(hWnd);}}case WM_DESTROY:{KillTimer(hWnd, ID_TIMER);PostQuitMessage(0);}break;default:return DefWindowProc(hWnd, uMsg, wParam,lParam);}}

3.总结

       其实这里面用到了Win32编程的大部分基础知识,如创建窗口、计时器回调函数和消息响应什么的。如果你刚学C++但觉得一点也没看懂,完全没有关系,只要学一点Windows的API编程很快就会了;如果你学过甚至是MFC的大牛,也给给评论吧(事实上,我真不知道屏幕保护程序是不是就只要写成一个exe文件)。

原创粉丝点击