day05 控件的使用

 

 

 

 

 

/**

GetDlgItem  获取窗口句柄
SendMessage  发送消息
MoveWindow
GetWindowText
getParent
ShowWindow

空间被用户操作的时候,会给父窗口发送消息 我们根据用户的动作去实现一些功能
我们需要使用代码控制去干一些事情,一般情况下都是GetDlgItem  获取窗口句柄,根据子控件ID获取到子控件,再通过
SendMessage发送消息控制控件的行为


标准控件【可以直接使用,数量少,功能简单】
按钮,复选框,单选框,静态文本框,图片,复合框,编辑框


通用控件【需要做一些初始化操作,数量多,功能强大】

*/

#include <Windows.h>
#include <CommCtrl.h>
#include "resource.h"
#include <windowsx.h>
INT_PTR CALLBACK Dlgproc(
	HWND hWnd,
	UINT uParam,
	WPARAM wParam,
	LPARAM lParam
);
// 居中函数
void CenterWindow(HWND hWnd);
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hInstPrev, PSTR cmdline, int cmdshow)
{
	
	DialogBoxW(hInst, MAKEINTRESOURCEW(IDD_DIALOG1), NULL, Dlgproc);

	return 0;
}

INT_PTR CALLBACK Dlgproc(
	HWND hWnd,
	UINT uParam,
	WPARAM wParam,
	LPARAM lParam
)
{
	switch (uParam)
	{
		case WM_INITDIALOG:
		{
			// DPI自适应
			UINT dpi = GetDpiForWindow(hWnd);
			int baseWidth = 500;
			int baseHeight = 350;
			int scaledWidth = MulDiv(baseWidth, dpi, 96);
			int scaledHeight = MulDiv(baseHeight, dpi, 96);

			SetWindowPos(hWnd, NULL, 0, 0, scaledWidth, scaledHeight,
				SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);

			// 居中显示
			CenterWindow(hWnd);

			// 方式1
			HWND hchecked_1 = GetDlgItem(hWnd, IDC_CHECK1);
			SendMessageW(hchecked_1, BM_SETCHECK, BST_CHECKED, 0);
			//方式2 
			SendDlgItemMessageW(hWnd, IDC_CHECK2, BM_SETCHECK, BST_CHECKED, 0);

			//方式3 需要引入#include <windowsx.h>

			Button_SetCheck(GetDlgItem(hWnd, IDC_CHECK3), BST_CHECKED);


			break;

		}
		case WM_CLOSE: {
			EndDialog(hWnd, 0);
			break;
		}
		case WM_COMMAND:
		{

			WORD controlId = LOWORD(wParam);
			switch (controlId)
			{
			case IDOK: {
				WCHAR buff[20] = { 0 };
				//WORD controlId = LOWORD(wParam);
				for (UINT btnid = IDC_CHECK1; btnid <= IDC_CHECK3; btnid++)
				{
					UINT Checked = SendDlgItemMessageW(hWnd, btnid, BM_GETCHECK, 0, 0);
					if (Checked)
					{
						GetDlgItemTextW(hWnd, btnid, buff, 20);
						MessageBoxW(hWnd, buff, L"结果", MB_OK);
					}
				}
				break;
			}
			case IDC_BUTTON1: {
				WCHAR buff[20] = { 0 };
				//WORD controlId = LOWORD(wParam);
				for (UINT btnid = IDC_RADIO1; btnid <= IDC_RADIO3; btnid++)
				{
					UINT Checked = SendDlgItemMessageW(hWnd, btnid, BM_GETCHECK, 0, 0);
					if (Checked)
					{
						GetDlgItemTextW(hWnd, btnid, buff, 20);
						MessageBoxW(hWnd, buff, L"结果", MB_OK);
					}
				}
				break;
			}
			default:
				break;
			}

			

			break;
		}
		default:
			return FALSE;
	}

	return TRUE;

}

// 居中函数
void CenterWindow(HWND hWnd)
{
	RECT rc;
	GetWindowRect(hWnd, &rc);

	int width = rc.right - rc.left;
	int height = rc.bottom - rc.top;

	int screenWidth = GetSystemMetrics(SM_CXSCREEN);
	int screenHeight = GetSystemMetrics(SM_CYSCREEN);

	SetWindowPos(hWnd, NULL,
		(screenWidth - width) / 2,
		(screenHeight - height) / 2,
		0, 0, SWP_NOZORDER | SWP_NOSIZE);
}

  

posted @ 2025-12-01 17:55  巨兽~墨菲特  阅读(2)  评论(0)    收藏  举报