C# cursor highlighting/follower

前端 未结 1 1534
-上瘾入骨i
-上瘾入骨i 2021-01-03 06:06

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

相关标签:
1条回答
  • 2021-01-03 06:47

    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);
        }
      }
    
    0 讨论(0)
提交回复
热议问题