我想创建一个动态宽度的按钮。 这是我的代码:
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”,则按钮不够宽。 如何设置动态宽度?
答案 0 :(得分:3)
好的,大卫,请下次提供更多信息,提及你不理解的一切,因为从评论中的问题我可以推断出你不仅不熟悉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:如何正确调整按钮的大小以适应其内容?