[英]Writing text to the system tray instead of an icon
我試圖在系統托盤中顯示2-3個可更新的字符,而不是顯示.ico文件 - 類似於CoreTemp在系統中顯示溫度時的操作嘗試:
我在WinForms應用程序中使用NotifyIcon以及以下代碼:
Font fontToUse = new Font("Microsoft Sans Serif", 8, FontStyle.Regular, GraphicsUnit.Pixel);
Brush brushToUse = new SolidBrush(Color.White);
Bitmap bitmapText = new Bitmap(16, 16);
Graphics g = Drawing.Graphics.FromImage(bitmapText);
IntPtr hIcon;
public void CreateTextIcon(string str)
{
g.Clear(Color.Transparent);
g.DrawString(str, fontToUse, brushToUse, -2, 5);
hIcon = (bitmapText.GetHicon);
NotifyIcon1.Icon = Drawing.Icon.FromHandle(hIcon);
DestroyIcon(hIcon.ToInt32);
}
遺憾的是,這產生的結果不如CoreTemp得到的結果:
您認為解決方案是增加字體大小,但超過8的任何內容都不適合圖像。 將位圖從16x16增加到32x32也沒有任何作用 - 它會調整大小。
然后就是我想要顯示“8.55”而不是“55”的問題 - 圖標周圍有足夠的空間但看起來無法使用。
有一個更好的方法嗎? 為什么Windows可以執行以下操作,但我不能?
更新:
感謝@NineBerry提供了一個很好的解決方案。 要添加,我發現Tahoma
是最好用的字體。
這給了我一個兩位數字符串的相當好看的顯示:
private void button1_Click(object sender, EventArgs e)
{
CreateTextIcon("89");
}
public void CreateTextIcon(string str)
{
Font fontToUse = new Font("Microsoft Sans Serif", 16, FontStyle.Regular, GraphicsUnit.Pixel);
Brush brushToUse = new SolidBrush(Color.White);
Bitmap bitmapText = new Bitmap(16, 16);
Graphics g = System.Drawing.Graphics.FromImage(bitmapText);
IntPtr hIcon;
g.Clear(Color.Transparent);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
g.DrawString(str, fontToUse, brushToUse, -4, -2);
hIcon = (bitmapText.GetHicon());
notifyIcon1.Icon = System.Drawing.Icon.FromHandle(hIcon);
//DestroyIcon(hIcon.ToInt32);
}
我改變了什么:
使用較大的字體大小,但將x和y偏移進一步向左和向上移動(-4,-2)。
在Graphics對象上設置TextRenderingHint以禁用消除鋸齒。
繪制超過2位數或字符似乎是不可能的。 圖標采用方形格式。 任何超過兩個字符的文本都意味着減少文本的高度。
選擇鍵盤布局(ENG)的示例實際上不是托盤區域中的通知圖標,而是它自己的shell工具欄。
顯示8.55的最佳效果:
private void button1_Click(object sender, EventArgs e)
{
CreateTextIcon("8'55");
}
public void CreateTextIcon(string str)
{
Font fontToUse = new Font("Trebuchet MS", 10, FontStyle.Regular, GraphicsUnit.Pixel);
Brush brushToUse = new SolidBrush(Color.White);
Bitmap bitmapText = new Bitmap(16, 16);
Graphics g = System.Drawing.Graphics.FromImage(bitmapText);
IntPtr hIcon;
g.Clear(Color.Transparent);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
g.DrawString(str, fontToUse, brushToUse, -2, 0);
hIcon = (bitmapText.GetHicon());
notifyIcon1.Icon = System.Drawing.Icon.FromHandle(hIcon);
//DestroyIcon(hIcon.ToInt32);
}
進行以下更改:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.