【发布时间】:2011-08-21 01:19:43
【问题描述】:
我正在尝试创建一个在系统托盘中显示一段文本的图标。 (显然,它不会超过几个字符。)
到目前为止我已经尝试过:
#include <tchar.h>
#include <Windows.h>
#include <Windowsx.h>
static HICON CreateIcon(LPCTSTR txt) {
HICON hIcon = NULL;
HDC hDC = NULL; {
HDC hDCScreen = GetDC(NULL);
if (hDCScreen != NULL) {
__try { hDC = CreateCompatibleDC(hDCScreen); }
__finally { ReleaseDC(NULL, hDCScreen); }
}
}
if (hDC != NULL) {
__try {
HFONT hFont = CreateFontIndirect(&ncm.lfMessageFont);
if (hFont != NULL) {
__try { SelectFont(hDC, hFont); }
__finally { DeleteFont(hFont); }
}
int width = GetSystemMetrics(SM_CXSMICON),
height = GetSystemMetrics(SM_CYSMICON);
HBITMAP hBmp = CreateCompatibleBitmap(hDC, width, height);
if (hBmp != NULL) {
__try {
HBITMAP hMonoBmp =
CreateCompatibleBitmap(hDC, width, height);
if (hMonoBmp != NULL) {
__try {
RECT rect = { 0, 0, width, height };
HGDIOBJ prev = SelectObject(hDC, hBmp);
__try {
SetBkMode(hDC, TRANSPARENT);
SetTextColor(hDC, RGB(255, 255, 255));
ICONINFO ii = { TRUE, 0, 0, hMonoBmp, hBmp };
int textHeight =
DrawText(hDC, txt, _tcslen(txt), &rect, 0);
if (textHeight != 0) {
hIcon = CreateIconIndirect(&ii);
}
} __finally { SelectObject(hDC, prev); }
} __finally { DeleteObject(hMonoBmp); }
}
} __finally { DeleteObject(hBmp); }
}
} __finally { DeleteDC(hDC); }
}
return hIcon;
}
使用此代码:
static void _tmain(int argc, TCHAR* argv[]) {
HICON hIcon = CreateIcon(_T("Hi"));
if (hIcon != NULL) {
__try {
NOTIFYICONDATA nid = { sizeof(nid) };
nid.hWnd = GetConsoleWindow();
BOOL success = Shell_NotifyIcon(NIM_ADD, &nid);
if (success) {
nid.uFlags = NIF_ICON;
nid.hIcon = hIcon;
success = Shell_NotifyIcon(NIM_MODIFY, &nid);
}
} __finally { DestroyIcon(hIcon); }
}
}
但我得到的只是一个单色位图,上面写着Hi,在黑色背景上用白色文本显示。 (如果我稍微改变一下RGB(255, 255, 255),比如RGB(255, 255, 254),它就会变成黑色,所以它是单色的。)
有什么想法吗?
(*注意:我不是寻找 MFC、ATL 或任何其他库解决方案,只是 Win32/GDI 调用。)
编辑:
这是目前的样子:
【问题讨论】:
-
请注意,它不叫“系统托盘”,也从未被称为“系统托盘”。这是任务栏通知区。
-
@Cody:是的,why use two syllables 九点什么时候可以?
-
不幸的是,在英语中,音节的数量和方便程度并不是决定短语正确性的主要因素。该区域称为通知区域。 Raymond Chen's blog article 是惯用的参考。你有没有想过为什么相关功能会提到“通知图标”?是的,您发现了一篇标题不准确的知识库文章。其中有很多。有一些信息完全不正确,尤其是关于 VB 的文章。
-
@Cody:博文倒数第三行准确地总结了我的感受。 ;)
-
感谢您的意见,马德赫德。
标签: winapi gdi system-tray trayicon