【发布时间】:2021-11-19 18:29:37
【问题描述】:
我一直在使用 Windows 模板库制作一个模态对话框,我需要在其中动态创建按钮并向它们添加工具提示。我似乎找不到正确的方法:
// CMyDialog.h
#pragma once
#include "stdafx.h"
class CMyDialog : public CDialogImpl<CIdleDialog> {
public:
enum { IDD = IDD_IDLEDIALOG };
protected:
BEGIN_MSG_MAP(CMyDialog)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
END_MSG_MAP()
LRESULT OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam,
BOOL &bHandled)
{
CRect dialog_rect(0, 0, 600, 400);
MoveWindow(&dialog_rect);
CenterWindow();
CButton btn;
CRect btn_rect(10, 10, 200, 30);
btn.Create(this->m_hWnd, btn_rect, L"Test Button",
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | BS_FLAT, NULL,
BTN_ID_OFFSET + 1);
CToolTipCtrl tooltip;
tooltip.Create(this->m_hWnd, rcDefault, NULL,
TTS_BALLOON | TTS_NOPREFIX);
TOOLINFO ti = {sizeof(ti)};
ti.hwnd = this->m_hWnd;
ti.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
ti.uId = (UINT_PTR)btn.m_hWnd;
ti.lpszText = (LPWSTR)L"THIS IS A TOOLTIP";
if (!tooltip.AddTool(&ti)) {
ocdbg("Could not add tooltip to button.\n");
}
tooltip.Activate(TRUE);
return TRUE;
}
};
关于我如何运行此对话框:
// main.cpp
#include "stdafx.h"
#include "CMyDialog.h"
CAppModule _Module;
int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance,
_In_ PWSTR pCmdLine, _In_ int nCmdShow)
{
AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES);
HRESULT h_res = _Module.Init(NULL, hInstance);
{
CMyDialog dialog;
dialog.DoModal();
}
_Module.Term();
return 0;
}
对tooltip.AddTool(&ti) 的调用返回0,表示失败。我假设这是因为该按钮不在我的 resource.h 文件中。有什么想法吗?
【问题讨论】:
-
CToolTipCtrl tooltip不应该是临时的。它应该被声明为成员数据。 -
另外,
ti.hwnd应该分配给btn.m_hWnd而不是this->m_hWnd。 -
@BarmakShemirani 我不认为这对这个案子很重要。当我将其设为数据成员时,没有任何变化。
-
@IInspectable ti.hwnd 成员是“包含该工具的窗口的句柄”。来自docs.microsoft.com/en-us/windows/win32/api/commctrl/…。你说的我试过了,但没有用。
-
文档中的措辞很糟糕,真的。它是在请求时处理文本查找的窗口的句柄。由于您没有使用
LPSTR_TEXTCALLBACK值,因此ti.hwnd值在很大程度上没有意义。
标签: c++ windows user-interface winapi wtl