我的第一個windows應用程序

創建一個windows應用程序,有以下基本步驟

  1. 創建窗口類
  2. 註冊窗口類
  3. 創建窗口
  4. 顯示窗口
  5. 消息循環
  6. 編寫窗口過程(消息處理函數)

代碼如下:

// Win32_01.cpp : Defines the entry point for the application.
//

#include "stdafx.h"

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	// 窗口類名,不要與系統的重複
	LPCTSTR lpszClassName = TEXT("My First Window");

	// 創建窗口類
	WNDCLASS wndclass;
	wndclass.style = 0;
	wndclass.lpfnWndProc = WindowProc;
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hInstance = hInstance;
	wndclass.hIcon = 0;
	wndclass.hCursor = 0;
	wndclass.hbrBackground = (HBRUSH)COLOR_MENU;
	wndclass.lpszMenuName = NULL;
	wndclass.lpszClassName = lpszClassName;

	// 註冊窗口類
	RegisterClass(&wndclass);

	// 創建窗口
	HWND hwnd = CreateWindow(
		lpszClassName,
		TEXT("我的第N個WIN32應用程序"),
		WS_OVERLAPPEDWINDOW,
		100,100,400,300,
		NULL,
		NULL,
		hInstance,
		NULL
		);
	if (hwnd == NULL)
	{
		MessageBox(hwnd, TEXT("創建窗口失敗"), TEXT("錯誤"), MB_OK);
		return 0;
	}

	// 顯示窗口
	ShowWindow(hwnd, SW_SHOW);

	// 消息循環
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	
	return 0;
}

LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch(uMsg)
	{
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	return DefWindowProc(hwnd, uMsg, wParam, lParam);
}


在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章