从托盘中删除图标
使用下面的代码会导致有时在调用 removeIconFromTray
方法后图标保留在托盘中,并且仅在用户将鼠标移到托盘中的图标上后才消失。
void CMyDlg::addIconToTray()
{
static HICON hIcon = ::LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON));
NOTIFYICONDATA data;
data.cbSize = sizeof(data);
data.hIcon = hIcon;
data.hWnd = m_hWnd;
strcpy (data.szTip, m_sTrayIconTip.c_str());
data.uFlags = NIF_ICON | NIF_TIP;
data.uID = (UINT)this;
Shell_NotifyIcon (NIM_ADD, &data);
}
void CMyDlg::removeIconFromTray()
{
NOTIFYICONDATA data;
data.cbSize = sizeof(data);
data.hWnd = m_hWnd;
data.uID = (UINT)this;
Shell_NotifyIcon (NIM_DELETE, &data);
}
这段代码有什么问题以及如何实现在从托盘中删除图标的代码完成工作后图标立即从托盘中消失?
Using the code below results in that sometimes an icon remains in a tray right after call to removeIconFromTray
method and disappears only after a user moves over an icon in tray.
void CMyDlg::addIconToTray()
{
static HICON hIcon = ::LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_MYICON));
NOTIFYICONDATA data;
data.cbSize = sizeof(data);
data.hIcon = hIcon;
data.hWnd = m_hWnd;
strcpy (data.szTip, m_sTrayIconTip.c_str());
data.uFlags = NIF_ICON | NIF_TIP;
data.uID = (UINT)this;
Shell_NotifyIcon (NIM_ADD, &data);
}
void CMyDlg::removeIconFromTray()
{
NOTIFYICONDATA data;
data.cbSize = sizeof(data);
data.hWnd = m_hWnd;
data.uID = (UINT)this;
Shell_NotifyIcon (NIM_DELETE, &data);
}
Whats wrong in this code and how to achieve that an icon disappears from a tray as soon as a code deleting it form there finished working?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个明显的问题是您无法初始化结构。您应该这样做:
除此之外,检查错误并调用 GetLastError 找出导致错误的原因。
One obvious problem is that you are failing to initialize your struct. You should do this:
Other than that check for errors and call GetLastError to find out what caused any error.
根据 MSDN:
Shell_NotifyIcon 函数
因此,您应该将 NOTIFYICONDATA 的相同数据传递给 Shell_NotifyIcon 函数。
这将正常工作。
或者,将数据保存到成员变量中。
According to MSDN:
Shell_NotifyIcon function
So, you should pass the same data of NOTIFYICONDATA to Shell_NotifyIcon function.
This will work properly.
Or, save the data to a member variable.
正如 DavidHeffernan 所说,您应该对
data
结构进行零初始化(您应该始终对传递给 Win32 API 函数的任何结构进行零初始化),例如:或者:
这样,任何未使用的字段都具有一致的和可预测的值。在您的情况下,当调用
NIM_DELETE
时,您没有初始化data
,因此它的uFlags
字段将具有随机位,这可能会导致< code>Shell_NotifyIcon() 会误解NOTIFYICONDATA
的内容并失败,因此您的图标不会被删除。As DavidHeffernan said, you should zero-initialize your
data
struct (you should ALWAYS zero-init any struct that you pass to a Win32 API function), eg:Or:
This way, any unused fields have consistent and predictable values. In your case, when calling
NIM_DELETE
, you are not initializingdata
, so itsuFlags
field will have random bits, which is likely to causeShell_NotifyIcon()
to misinterpret the content of yourNOTIFYICONDATA
and fail, and thus your icon is not removed.