C#光标高亮/跟随光标、高亮

2023-09-03 04:21:07 作者:何况那算什么伤〝

如何突出系统光标?像许多屏幕录制应用程序做的。理想情况下,我想围绕它显示一个光环。 谢谢

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

推荐答案

对于一个纯粹的管理解决方案,以下code将利用在桌面上的椭圆在当前鼠标光标位置。

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

通过使用定时器您可以更新鼠标的位置每20ms例如,绘制新的万圣节(椭圆形)。

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

有,我能想到的其他更有效的方法,但是他们会用系统钩子要求unamanged code。看看SetWindowsHookEx函数以获取更多信息。

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