在光标周围画一个圆圈(C#)

时间:2015-07-24 12:45:05

标签: c# cursor console-application leap-motion

使用C#;

我正在尝试使用Leap Motion传感器制作应用程序,将手指移动映射到光标移动。在屏幕上,我想在光标周围画一个圆圈。

经过一番搜索,我发现有人试图做同样的事情(Leap Motion排除在外)Want a drawn circle to follow my mouse in C#。 那里的代码出现了:

private void drawCircle(int x, int y)
{
    Pen skyBluePen = new Pen(Brushes.DeepSkyBlue);
    Graphics graphics = CreateGraphics();
    graphics.DrawEllipse(
        skyBluePen, x - 150, y - 150, 300, 300);
    graphics.Dispose();
    this.Invalidate();
}

我做了一些改动,使其适用于我的应用程序:

private void drawCircle(int x, int y, int size)
{
    Pen skyBluePen = new Pen(Brushes.DeepSkyBlue);
    Graphics graphics = Graphics.FromHwnd(IntPtr.Zero);
    graphics.DrawEllipse(
        skyBluePen, x - size / 2, y - size / 2, size, size);
    graphics.Dispose();
}

我必须进行一些更改的原因是因为我的应用程序从控制台运行而不使用表单。这意味着我无法使用其他问题中提供的解决方案。

上面的代码确实绘制了圆圈,但它们并没有消失,如下图所示:

enter image description here 需要注意的是,即使控制台不是活动窗口,我的应用程序也需要运行(现在可以正常工作)。

现在,我对C#很陌生,所以可能解决方案非常简单,但我找不到它。

所以简而言之:我希望它只有最后绘制的圆圈可见。

3 个答案:

答案 0 :(得分:2)

您需要Panel,Form或继承自Control的内容。 然后,您可以覆盖OnPaint或绑定到Paint事件。

根据这里的答案:draw on screen without form

这样做有效,你只能在屏幕上看到你的圈子,你 ALT + TAB,因为它是最顶层的。

此外,事件正在进行,这意味着Windows无论如何都可以使用。

一个例外是,它目前只使用主屏幕来显示圆圈。

如果计时器太慢,您可以在绘图后调用Invalidate();,但我不确定这是否是性能问题。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.DoubleBuffered = true;

        BackColor = Color.White;
        FormBorderStyle = FormBorderStyle.None;
        Bounds = Screen.PrimaryScreen.Bounds;
        TopMost = true;
        TransparencyKey = BackColor;

        timer1.Tick += timer1_Tick;
    }

    Timer timer1 = new Timer() { Interval = 15, Enabled = true};

    protected override void OnPaint(PaintEventArgs e)
    {
        DrawTest(e.Graphics);
        base.OnPaint(e);
    }

    private void DrawTest(Graphics g)
    {
        var p = PointToClient(Cursor.Position);
        g.DrawEllipse(Pens.DeepSkyBlue, p.X - 150, p.Y - 150, 300, 300);
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        Invalidate();
    }
}

答案 1 :(得分:0)

我试着帮助你...... 也许你可以使用计时器来显示圆圈,然后,例如,1秒,隐藏它。 可能是一个解决方案吗?

答案 2 :(得分:0)

每次你想画一个圆圈:

  • 恢复上一张图之前的图像,
  • 将矩形保存到绘制圆圈的位置
  • 画圆圈。

此过程保存周围矩形的图像:

Bitmap saveBitmap = null ;
Rectangle saveRect ;

private void SaveCircleRect(Graphics graphics,int x, int y, int size)
{
    saveBitmap  = new Bitmap(2*size,2*size,graphics);
    saveRect = new Rectangle(x-size/2, y-Size/2, Width, Height);
 }

此过程使用保存的矩形恢复屏幕图像:

private void RestoreCircleRect(Graphics graphics)
{
   if (saveBitmap!=null) graphics.DrawImage(saveBitmap,saveRect);
}

但是,当关注的应用程序发生变化或重新调整/重新绘制时,您将面临<很多问题。

替代解决方案可以显示4个最薄的最顶层表单,代表正方形的4个边,并在光标移动时更改它们的位置。