Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to Make the Mouse Freeze c#

Tags:

c#

.net

i want the mouse to freez (cant move) when mouse down thanks

like image 249
sam Avatar asked Dec 01 '22 04:12

sam


1 Answers

I used a tableLayoutPanel for your reference (Just remember to implement the code to the Control that is in the front):

OPTION1: Reset the mouse position:

Define two global variables:

bool mousemove = true;
Point currentp = new Point(0, 0);

Handel MouseDown Event to update mousemove :

private void tableLayoutPanel1_MouseDown(object sender, MouseEventArgs e)
{
    int offsetX = (sender as Control).Location.X + this.Location.X;
    int offsetY = (sender as Control).Location.Y + this.Location.Y;
    mousemove = false;
    currentp = new Point(e.X+offsetX, e.Y+offsetY); //or just use Cursor.Position
}

Handel MouseMove to disable/enable move:

 private void tableLayoutPanel1_MouseMove(object sender, MouseEventArgs e)
    {
        if (!mousemove)
        {
            this.Cursor = new Cursor(Cursor.Current.Handle);
            Cursor.Position = currentp;
        }
    }

Reset mousemove while Mouseup

private void tableLayoutPanel1_MouseUp(object sender, MouseEventArgs e)
    {
        mousemove = true;
    } 

OPTION2: Limit mouse clipping rectangle:

Limit it while MouseDown:

private void tableLayoutPanel1_MouseDown(object sender, MouseEventArgs e)
        {            
            this.Cursor = new Cursor(Cursor.Current.Handle);
            Cursor.Position = Cursor.Position;
            Cursor.Clip = new Rectangle(Cursor.Position, new Size(0, 0));
        }

Release it after MouseUp:

 private void tableLayoutPanel1_MouseUp(object sender, MouseEventArgs e)
    {
        this.Cursor = new Cursor(Cursor.Current.Handle);
        Cursor.Position = Cursor.Position;
        Cursor.Clip = Screen.PrimaryScreen.Bounds;
    }  
like image 89
Bolu Avatar answered Dec 03 '22 17:12

Bolu