c++自定义按钮图标

c++ custom button icon

本文关键字:图标 按钮 自定义 c++      更新时间:2023-10-16

我想创建一个动态宽度的按钮。下面是我的代码:

CreateWindowEx(BS_PUSHBUTTON, "BUTTON", "OK",
            WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
            50, 220, 100, 24, hwnd,
            (HMENU)ID_BUTTON,
            GetModuleHandle(NULL),
            0);

但是如果我把标签"OK"改为"SOMETHING LONGER",那么按钮就不够宽了。如何设置动态宽度?

试试Button_GetIdealSize宏。


好的,David,请下次提供更多的信息,提到你不理解的一切,因为从你在评论中的问题中我可以推断出你不仅不熟悉Win API,而且对C/c++编程也是非常陌生的。

HWND buttonHandle = CreateWindowEx(BS_PUSHBUTTON, "BUTTON", "OK",
                                   WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
                                   50, 220, 100, 24,
                                   hwnd,
                                   (HMENU)ID_BUTTON,
                                   GetModuleHandle(NULL),
                                   0);
SIZE size;
if (!Button_GetIdealSize(buttonHandle, &size)) {
  // Call of `Button_GetIdealSize` failed, do proper error handling here.
  // For that you have various options:
  // 1. Exit current scope and return error code;
  // 2. Throw an exception;
  // 3. Terminate execution of your application and print an error message.
  // Of course these options can be mixed.
  // If you don't understand what I'm talking about here, then either skip this
  // check or start reading books on software development with C/C++.
}
// At this point `size` variable was filled with proper dimensions.
// Now we can use it to actually resize our button...
if (!MoveWindow(buttonHandle, 50, 220, (int)size.cx, (int)size.cy, TRUE)) {
  // Call of `MoveWindow` failed, do proper error handling here, again.
}
// We are done!

注意:你的题目提错了。c++与按钮和Win API没有任何关系,顺便说一下,这是纯C。更好的标题是:Win API:如何正确调整按钮大小以适合其内容?