1

我想制作一个动态宽度的按钮。这是我的代码:

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”,则按钮不够宽。如何设置动态宽度?

4

1 回答 1

3

试试Button_GetIdealSize 宏


好的,大卫,下次请提供更多信息,把你不明白的地方说出来,因为从你评论中的问题我可以推断你不仅不熟悉 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:如何正确调整按钮大小以适应其内容?

于 2013-03-17T20:23:41.547 回答