David Amaral David Amaral - 2 months ago 11
C# Question

Hide mouse cursor after certain inactive mouse time in a WebBrowser Control

I'm trying to make the mouse cursor disappear after a certain time when the mouse isn't moving. There's already a question on this but the WebBrowser Control form doesn't have Mouse events. I have this code that was mentioned on the question linked above:

public partial class Form1 : Form
{
public TimeSpan TimeoutToHide { get; private set; }
public DateTime LastMouseMove { get; private set; }
public bool IsHidden { get; private set; }

public Form1()
{
InitializeComponent();
TimeoutToHide = TimeSpan.FromSeconds(5);
this.MouseMove += new MouseEventHandler(Form1_MouseMove);
}

void Form1_MouseMove(object sender, MouseEventArgs e)
{
LastMouseMove = DateTime.Now;

if (IsHidden)
{
Cursor.Show();
IsHidden = false;
}
}

private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan elaped = DateTime.Now - LastMouseMove;
if (elaped >= TimeoutToHide && !IsHidden)
{
Cursor.Hide();
IsHidden = true;
}
}
}

Answer

The WebBrowserControl doesn't support MouseMove event. Instead you can use MouseMove event of WebBrowser.Document.Body.

Then apply the logic which you are using for showing and hiding cursor. In a timer Tick event check if the last movement was before a specific time, hide the cursor using Cursor.Hide. Also in MouseMove show the cursor using Cursor.Show method.

DateTime? lastMovement;
bool hidden = false;
void Form1_Load(object sender, EventArgs e)
{
    webBrowser1.Navigate("http://www.google.com");
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    webBrowser1.Document.MouseMove += Document_MouseMove;
}
void Document_MouseMove(object sender, HtmlElementEventArgs e)
{
    lastMovement = DateTime.Now;
    if (hidden)
    {
        Cursor.Show();
        hidden = false;
    }
}
private void timer1_Tick(object sender, EventArgs e)
{
    if (!lastMovement.HasValue)
        return;
    TimeSpan elaped = DateTime.Now - lastMovement.Value;
    if (elaped >= TimeSpan.FromSeconds(2) && !hidden)
    {
        Cursor.Hide();
        hidden = true;
    }
}

Note

  • The job of bool hidden is to keep balance between Show and Hide, because as mentioned in documentations:

    The Show and Hide method calls must be balanced. For every call to the Hide method there must be a corresponding call to the Show method.

  • Subscribe for MouseMove when the document completed, because Document would be null before completing DocumentCompleted event raise.

  • I checked if lastMovement doesn't have value then didn't hide the cursor, to prevent hiding the cursor at startup before the user moves mouse over the control.

Comments