保证工具栏分隔符在多次 TB_ADDBUTTONS 调用中的正确间距





5.00/5 (2投票s)
解决方案:如果工具栏通过单个 TB_ADDBUTTONS 调用逐个按钮创建,则分隔符的宽度计算不正确。
引言
我通过单个 TB_ADDBUTTONS
消息调用来创建我的工具栏。我也使用 TB_ADDBUTTONS
消息调用来创建分隔符。但是分隔符的宽度一开始太小,然后随着每个分隔符的增加而增加。
背景
为了获得正确的分隔符宽度(每个 8px),TBSTYLE_SEP
不应单独添加到工具栏。为了解决这个问题,我更改了我的 API 并添加了 bPrependSeparator
参数。结果如下
Using the Code
我知道 - 可以写得更短,但代码可读且能完成它应该做的事情
/// <summary>
/// Adds a new button to the tool bar.
/// </summary>
/// <param name="hBmpImage">The handler of the tool bar button image bitmap.
/// Can be <c>NULL</c>, if <c>byStyle</c> doesn't need an image.</param>
/// <param name="hBmpMask">The handler of the tool bar button mask bitmap.
/// Can be <c>NULL</c>, if transparency is not required.</param>
/// <param name="uiCommandID">The tool bar button command ID, that is in sync
/// with the menu item command ID.</param>
/// <param name="byState">The initial tool bar button state.</param>
/// <param name="byStyle">The tool bar button style.</param>
/// <param name="wszText">The optional text to display below the image.</param>
/// <param name="bPrependSeparator">The flag determining whether to prepend a separator.
/// </param>
/// <returns>The number of remaining image list slots for tool bar button images.</returns>
/// <remarks>Can still be called like this to create an not-prepended separator
/// (but the space isn't correct):
/// pToolBar->AddButton(NULL, NULL, (UINT)0, TBSTATE_ENABLED, TBSTYLE_SEP);</remarks>
UINT OgwwToolBar::AddButton(HBITMAP hBmpImage, HBITMAP hBmpMask,
UINT uiCommandID, BYTE byState,
BYTE byStyle, LPCWSTR wszText, BOOL bPrependSeparator)
{
if (hBmpImage != NULL)
{
::ImageList_Add(_hImageList, hBmpImage, hBmpMask);
_wBitmapUsed++;
}
if (bPrependSeparator != FALSE)
{
TBBUTTON tbb[2];
::ZeroMemory(tbb, sizeof(tbb));
tbb[0].iBitmap = 0;
tbb[0].idCommand = 0;
tbb[0].fsState = TBSTATE_ENABLED;
tbb[0].fsStyle = TBSTYLE_SEP;
tbb[0].iString = 0;
tbb[1].iBitmap = (_hImageList != NULL) ? _wBitmapUsed - 1 : 0;
tbb[1].idCommand = uiCommandID;
tbb[1].fsState = byState;
tbb[1].fsStyle = byStyle;
tbb[1].iString = 0; // SendMessageW(hToolBar, TB_ADDSTRING, 0, (LPARAM)wszText);
// Try this if it doesn't work out right away:
//::SendMessageW((HWND)_hHandle, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
::SendMessageW((HWND)_hHandle, TB_ADDBUTTONS, 2, (LPARAM)tbb);
}
else
{
TBBUTTON tbb;
::ZeroMemory(&tbb, sizeof(tbb));
tbb.iBitmap = (_hImageList != NULL) ? _wBitmapUsed - 1 : 0;
tbb.idCommand = uiCommandID;
tbb.fsState = byState;
tbb.fsStyle = byStyle;
tbb.iString = 0; // SendMessageW(hToolBar, TB_ADDSTRING, 0, (LPARAM)wszText);
::SendMessageW((HWND)_hHandle, TB_ADDBUTTONS, 1, (LPARAM)&tbb);
}
return (_wBitmapCount - _wBitmapUsed);
}
编程愉快!
关注点
并非所有允许/编译通过的代码都能正常工作。
历史
- 2020 年 1 月 16 日:初始版本