Reputation: 1146
I would like to make a button with dynamic width. Here is my code:
CreateWindowEx(BS_PUSHBUTTON, "BUTTON", "OK",
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
50, 220, 100, 24, hwnd,
(HMENU)ID_BUTTON,
GetModuleHandle(NULL),
0);
But if I change the label "OK" to "SOMETHING LONGER", then the button is not wide enough. How can I set dynamic width?
Upvotes: 1
Views: 635
Reputation: 17019
Try Button_GetIdealSize macro.
OK, David, please next time supply more information, mention everything you don't understand, because from your questions in comments I can infer that you are not only unfamiliar with Win API, but you are also very new to the C/C++ programming in general.
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!
NOTE: The title of your question is incorrectly posed. C++ has nothing to do with buttons and Win API in particular, which is pure C by the way. Much better title would be: Win API: How to properly resize a button to fit its contents?
Upvotes: 3