我正在尝试创建一个在系统托盘中显示一段文本的图标。(显然,它不会超过几个字符。)
到目前为止,我已经尝试过:
#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 调用。)
编辑:
这是它目前的样子: