C語言實現SDK窗口編程
阿新 • • 發佈:2017-09-22
c/c++
//--------------------------------------------------------------------------- #include <windows.h> //=========================================================================== long __stdcall WndProc(HWND hwnd,UINT msg,WPARAM WParam,LPARAM LParam) { switch(msg) { case WM_CLOSE: PostQuitMessage(0); break; case WM_LBUTTONDOWN: MessageBoxA(0,"ok","提示",0); PostQuitMessage(0); break; case WM_PAINT: { HDC hdc; hdc = GetDC(hwnd); RECT rect; GetClientRect(hwnd,&rect); rect.left = rect.right/2; rect.top = rect.bottom/2; rect.right = rect.left+50; rect.bottom = rect.top+30; DrawText(hdc,"hello",5,&rect,0); ReleaseDC(NULL,hdc); } default: return DefWindowProc(hwnd,msg,WParam,LParam); } return 0; } WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPreHinstance, LPSTR, int) { g_hIns = hInstance; WNDCLASS theClass ={0}; char * lpszClassName = "myClass"; char * lpszTitle = "測試窗口"; HWND hwnd; MSG msg; theClass.style = 0;//缺省窗口風格 theClass.lpfnWndProc = WndProc; theClass.cbClsExtra = 0;//窗口類無擴展 theClass.cbWndExtra = 0;//窗口實例無擴展 theClass.hInstance = hInstance; //窗口的最小化圖標為缺省圖標,即窗口左上角圖標 //VC中資源ID為IDI_APPLICATION //在BCB中資源名為MAINICON theClass.hIcon=LoadIcon(hInstance,"MAINICON"); theClass.hCursor=LoadCursor(NULL,IDC_ARROW); //窗口采用箭頭光標 theClass.hbrBackground=(HBRUSH)(GetStockObject(WHITE_BRUSH)); //窗口背景為白色 theClass.lpszMenuName=NULL; //窗口無菜單 theClass.lpszClassName= lpszClassName; //窗口類名為"窗口" if(!RegisterClass(&theClass)) //如果註冊失敗 發出警告 { MessageBeep(0); return FALSE; } hwnd=CreateWindow( lpszClassName, //窗口類名 lpszTitle, //窗口標題名 WS_OVERLAPPEDWINDOW, //窗口的風格 CW_USEDEFAULT, //窗口左上角坐標值為缺省值 CW_USEDEFAULT, 500, 300, //窗口的寬和高 NULL, //此窗口無父窗口 NULL, //此窗口無子菜單 hInstance, //創建此窗口的應用程序的當前句柄 NULL //不使用該值 ); ShowWindow(hwnd,SW_SHOW); UpdateWindow(hwnd); while(true) { if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if (msg.message == WM_QUIT) break; TranslateMessage(&msg); DispatchMessage(&msg); } // if (GetMessage (&msg, NULL, 0, 0)) // { // TranslateMessage (&msg) ; // DispatchMessage (&msg) ; // } // else // break; } return msg.wParam; //消息循環結束 即程序結束時 將信息返回系統 }
PeekMessage與GetMessage函數處理不相同,兩種方式都可以.PeekMessage是不阻塞的,GetMessage是線程阻塞的,內部處理退出消息,所以不用判斷退出消息,關閉時,就跳到break結束循環。要在WM_PAINT消息中繪圖,可用如下代碼:
PAINTSTRUCT ps ={0}; HDC hdc = BeginPaint(hwnd,&ps); //HPEN hPen = GetStockObject(WHITE_PEN); HPEN hPen = CreatePen(PS_DASHDOTDOT,1,RGB(255 , 0 , 0 )); HGDIOBJ oldPen = (HGDIOBJ)SelectObject(hdc,hPen); if(!oldPen) { int err = GetLastError(); char buff[20]={0}; itoa(err,buff,10); OutputDebugStringA(buff); } //畫矩形 Rectangle(hdc,20,30,80,120); //畫線 MoveToEx ( hdc , 20 , 10 , NULL ); LineTo( hdc , 200 ,100); SelectObject(hdc, oldPen); DeleteObject(hPen); EndPaint(hwnd,&ps);
C語言實現SDK窗口編程