简体   繁体   中英

C# cursor highlighting/follower

How to highlight the system cursor? Like many screen recording applications do. Ideally, I'd like to display a halo around it. Thanks

For a purely managed solution, the following code will draw an ellipse on the desktop at the current mouse cursor position.

Point pt = Cursor.Position; // Get the mouse cursor in screen coordinates

using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
{        
  g.DrawEllipse(Pens.Black, pt.X - 10, pt.Y - 10, 20, 20);
}

By using a timer you can update the mouse position every 20ms for example and draw the new hallow (ellipse).

There are other more efficient ways that I can think of, but they would require unamanged code using system hooks. Take a look at SetWindowsHookEx for more info on this.

Update: Here is a sample of the solution I described in my comments, this is just rough and ready for testing purposes.

  public partial class Form1 : Form
  {
    private HalloForm _hallo;
    private Timer _timer;

    public Form1()
    {
      InitializeComponent();
      _hallo = new HalloForm();
      _timer = new Timer() { Interval = 20, Enabled = true };
      _timer.Tick += new EventHandler(Timer_Tick);
    }

    void Timer_Tick(object sender, EventArgs e)
    {
      Point pt = Cursor.Position;
      pt.Offset(-(_hallo.Width / 2), -(_hallo.Height / 2));
      _hallo.Location = pt;

      if (!_hallo.Visible)
      {
        _hallo.Show();
      }
    }    
  }

  public class HalloForm : Form
  {        
    public HalloForm()
    {
      TopMost = true;
      ShowInTaskbar = false;
      FormBorderStyle = FormBorderStyle.None;
      BackColor = Color.LightGreen;
      TransparencyKey = Color.LightGreen;
      Width = 100;
      Height = 100;

      Paint += new PaintEventHandler(HalloForm_Paint);
    }

    void HalloForm_Paint(object sender, PaintEventArgs e)
    {      
      e.Graphics.DrawEllipse(Pens.Black, (Width - 25) / 2, (Height - 25) / 2, 25, 25);
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM