C# cursor highlighting/follower

妖精的绣舞 提交于 2019-12-19 04:14:35

问题


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


回答1:


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);
    }
  }


来源:https://stackoverflow.com/questions/2622612/c-sharp-cursor-highlighting-follower

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!