将文本写入系统托盘而不是图标

时间:2016-04-02 22:43:29

标签: c# .net system-tray notifyicon

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

enter image description here

我在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得到的结果:

enter image description here

您认为解决方案是增加字体大小,但超过8的任何内容都不适合图像。将位图从16x16增加到32x32也没有任何作用 - 它会调整大小。

然后就是我想要显示“8.55”而不是“55”的问题 - 图标周围有足够的空间但看起来无法使用。

enter image description here

有更好的方法吗?为什么Windows可以执行以下操作,但我不能?

enter image description here

更新

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

1 个答案:

答案 0 :(得分:14)

这给了我一个两位数字符串的漂亮外观:

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以禁用消除锯齿功能。

  3. 似乎无法绘制超过2位数或字符。图标采用方形格式。任何超过两个字符的文本都意味着减少文本的高度。

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

    我能达到的最好的显示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. 使用非常窄的字体Trebuchet MS。
    2. 使用单引号代替点,因为它的边缘空间较小。
    3. 使用字体大小10并充分调整偏移量。