cpg_icon02.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <windows.h>
  2. #define BUTTON_SIZE 40
  3. LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
  4. // `shell32.dll` 中图标的索引
  5. int iconIndexes[16] = {4, 5, 7, 10, 14, 16, 18, 21,
  6. 23, 27, 31, 35, 39, 43, 45, 60};
  7. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
  8. LPSTR lpCmdLine, int nCmdShow) {
  9. // 注册窗口类
  10. const char CLASS_NAME[] = "SimpleWindowClass";
  11. WNDCLASS wc = {};
  12. wc.lpfnWndProc = WindowProc;
  13. wc.hInstance = hInstance;
  14. wc.lpszClassName = CLASS_NAME;
  15. wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  16. RegisterClass(&wc);
  17. // 窗口宽度和高度
  18. int w = 320;
  19. int h = 80;
  20. // 计算窗口显示位置
  21. int x = (GetSystemMetrics(SM_CXSCREEN) - w) / 2;
  22. int y = (GetSystemMetrics(SM_CYSCREEN) - h) / 2;
  23. // 创建窗口
  24. HWND hwnd =
  25. CreateWindowEx(WS_EX_TOPMOST, CLASS_NAME, "", WS_POPUP | WS_VISIBLE, x, y,
  26. w, h, NULL, NULL, hInstance, NULL);
  27. if (!hwnd) {
  28. return 0;
  29. }
  30. // 显示窗口
  31. ShowWindow(hwnd, nCmdShow);
  32. // 进入消息循环
  33. MSG msg = {};
  34. while (GetMessage(&msg, NULL, 0, 0)) {
  35. TranslateMessage(&msg);
  36. DispatchMessage(&msg);
  37. }
  38. return 0;
  39. }
  40. LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,
  41. LPARAM lParam) {
  42. switch (uMsg) {
  43. case WM_CREATE: {
  44. // 获取 shell32.dll 的路径
  45. char shell32Path[MAX_PATH];
  46. GetSystemDirectory(shell32Path, MAX_PATH);
  47. strcat(shell32Path, "\\shell32.dll");
  48. // 创建16个按钮并加载不同图标
  49. for (int i = 0; i < 16; ++i) {
  50. int x = (i % 8) * BUTTON_SIZE;
  51. int y = (i / 8) * BUTTON_SIZE;
  52. HWND hButton = CreateWindow(
  53. "BUTTON", "", WS_CHILD | WS_VISIBLE | BS_ICON, x, y, BUTTON_SIZE,
  54. BUTTON_SIZE, hwnd, (HMENU)(1000 + i), GetModuleHandle(NULL), NULL);
  55. // 使用 ExtractIcon 从 shell32.dll 中提取图标
  56. HICON hIcon =
  57. ExtractIcon(GetModuleHandle(NULL), shell32Path, iconIndexes[i]);
  58. SendMessage(hButton, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
  59. }
  60. return 0;
  61. }
  62. case WM_DESTROY:
  63. PostQuitMessage(0);
  64. return 0;
  65. }
  66. return DefWindowProc(hwnd, uMsg, wParam, lParam);
  67. }