绘制放置在Cursor.Current左下角的工具提示

时间:2013-06-04 14:19:17

标签: .net winforms cursor drawing tooltip

我正在尝试在光标左下角绘制工具提示。我正在使用以下代码来计算de Cursor底点:

    private void PaintTooltip()
    {
       ...
       Point target = this.PointToClient(GetCursorPoint()));
       ...
       // paint the tooltip at point target
    }

    private Point GetCursorPoint()
    {
        return new Point(
            Cursor.Position.X,
            Cursor.Position.Y + Cursor.Current.Size.Height - Cursor.Current.HotSpot.Y);
    }

提示Cursor.Current.Hostpot通常有0值。

使用这段代码,我得到了一些像素:

enter image description here

为什么我明白这一点?

1 个答案:

答案 0 :(得分:1)

因为光标的标准尺寸是32x32像素,但大多数像素都是透明的,所以你必须通过检查光标本身来确定“实际”高度。

例如,我将默认光标绘制到这样的位图:

        Bitmap bmp = new Bitmap(Cursor.Current.Size.Width, Cursor.Current.Size.Height);
        using (Graphics g = Graphics.FromImage(bmp))
        {
            g.Clear(Color.Red);
            Cursor.Current.Draw(g, new Rectangle(new Point(0, 0), bmp.Size));
        }
        pictureBox1.Image = bmp;

所以你可以清楚地看到光标相对于它的实际大小有多大:

enter image description here

编辑:这是一个根据光标的“实际”大小在当前光标位置下方绘制一个矩形的示例:

    private void button1_Click(object sender, EventArgs e)
    {
        Rectangle bounds = CursorBounds();
        Point pt = new Point(Cursor.Position.X + bounds.Left, Cursor.Position.Y + bounds.Bottom);
        ControlPaint.DrawReversibleFrame(new Rectangle(pt, new Size(100, 30)), this.BackColor, FrameStyle.Dashed);
    }

    private Rectangle CursorBounds()
    {
        using (Bitmap bmp = new Bitmap(Cursor.Current.Size.Width, Cursor.Current.Size.Height))
        {
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.Transparent);
                Cursor.Current.Draw(g, new Rectangle(new Point(0, 0), bmp.Size));

                int xMin = bmp.Width;
                int xMax = -1;
                int yMin = bmp.Height;
                int yMax = -1;

                for (int x = 0; x < bmp.Width; x++)
                {
                    for (int y = 0; y < bmp.Height; y++)
                    {
                        if (bmp.GetPixel(x, y).A > 0)
                        {
                            xMin = Math.Min(xMin, x);
                            xMax = Math.Max(xMax, x);
                            yMin = Math.Min(yMin, y);
                            yMax = Math.Max(yMax, y);
                        }
                    }
                }
                return new Rectangle(new Point(xMin, yMin), new Size((xMax - xMin) + 1, (yMax - yMin) + 1));
            }
        }
    }

我真的不确定是否有更好的方法来做到这一点...... = \