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

MSO*_*ACC 14 .net c# system-tray notifyicon

我试图在系统托盘中显示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);
}
Run Code Online (Sandbox Code Playgroud)

遗憾的是,这产生的结果不如CoreTemp得到的结果:

在此输入图像描述

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

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

在此输入图像描述

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

在此输入图像描述

更新:

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

Nin*_*rry 17

这给了我一个两位数字符串的相当好看的显示:

在此输入图像描述

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);
}
Run Code Online (Sandbox Code Playgroud)

我改变了什么:

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

  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);
}
Run Code Online (Sandbox Code Playgroud)

进行以下更改:

  1. 使用非常窄的字体Trebuchet MS.
  2. 使用单引号而不是点,因为它的侧面空间较小.
  3. 使用字体大小10并充分调整偏移量.

  • 您需要一行:DestroyIcon(hIcon) 以防止应用程序在大约 50 分钟后因内存泄漏而退出。 (4认同)
  • 另外,只是说我发现“Tahoma”是此处使用的最佳字体。 (2认同)