2016-04-02 146 views
7

我试图在系统托盘中显示2-3个可更新字符,而不是显示.ico文件 - 类似于CoreTemp在系统中显示温度时所做的操作尝试:将文本写入系统托盘而不是图标

enter image description here

我用下面的代码一起使用的NotifyIcon在我的WinForms应用程序:

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得到:

enter image description here

你会认为解决办法是增加字体大小,但任何尺寸超过8不适合在图像内。将位图从16x16增加到32x32也不会做任何事 - 它会被调整大小。

然后出现了我想要显示“8.55”而不是“55”的问题 - 图标周围有足够的空间,但看起来不可用。

enter image description here

有没有更好的方式来做到这一点?为什么窗户可以做到以下,但我不能?

enter image description here

更新:

感谢@NineBerry一个很好的解决方案。要添加,我发现Tahoma是最好的字体使用。

+1

我希望其他应用程序只使用了一组内置的图标,而不是试图产生他们即时 –

回答

9

这给了我两个数字串的挺好看的显示:

enter image description here

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); 
} 

我改变什么:

  1. 用较大的字体大小,但移动x和y进一步向左和向上偏移(-4,-2)。

  2. 在Graphics对象上设置TextRenderingHint以禁用消除锯齿。

看起来不可能画出两个以上的数字或字符。图标有一个方形格式。任何超过两个字符的文字都意味着文本的高度会减少很多。

您选择键盘布局(ENG)的示例实际上不是托盘区域中的通知图标,而是它自己的外壳工具栏。


我可以实现的最佳显示方式8。55:

enter image description here

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); 
} 

具有以下变化:

  1. 使用分析天平MS这是一个非常窄的字体。
  2. 使用单引号而不是点,因为它在侧面的空间较少。
  3. 使用字体大小10并适当地调整偏移量。
+0

很大的反响,非常感谢 – MSOACC

+1

另外,只是说,我觉得“宋体”成为这里使用的最好的字体。 – MSOACC