Search code examples
c#winformsmouseironpython

How to release captured (clipped) cursor in winforms?


I was trying to implement this example with IronPython. I succeeded to capture the cursor using this method:

def MoveCursor(self):
    #Set the Current cursor, move the cursor's Position,
    #and set its clipping rectangle to the form.
    if self.MouseLocked == False:
        self.Cursor = System.Windows.Forms.Cursor(System.Windows.Forms.Cursor.Current.Handle)
        System.Windows.Forms.Cursor.Position = System.Drawing.Point(self.Cursor.Position.X - 50, self.Cursor.Position.Y - 50)
        System.Windows.Forms.Cursor.Clip = System.Drawing.Rectangle(self.Location, self.Size)
        self.MouseLocked = True
    elif self.MouseLocked == True:
        self.Cursor = System.Windows.Forms.Cursor(System.Windows.Forms.Cursor.Current.Handle)
        #System.Windows.Forms.Cursor.Position = System.Drawing.Point(self.Cursor.Position.X - 50, self.Cursor.Position.Y - 50)
        System.Windows.Forms.Cursor.Clip = None
        self.MouseLocked = False

I tried using a class variable to toggle the capturing but it doesn't work as I expected. How do I release the mouse? Which method or event do I need to use?

update: I tried using self.Cursor.Dispose(), but that just made my cursor invisible :D, kinda funny, but not what I needed.


Solution

  • "Releasing" the clipping of the cursor is called "clearing" from a technical aspect, and will yield better search results. There are many other examples (here is one) on the web dealing with this exact issue in dedicated C#, and doing the same with ironpython is no different.

    As you review the documentation, the first sentence in particular implicitly answers your question (emphasis mine):

    The following code example creates a cursor from the Current cursor's Handle, changes its position and clipping rectangle.

    To clear a previously set position and clipping rectangle, you need to set the Clip property to a new, empty Rectangle:

    Cursor.Clip = new Rectangle();
    

    This effectively clears the position and clipping rectangle of the cursor. Your particular case would place it in your elif block:

    elif self.MouseLocked == True:
        ...
        System.Windows.Forms.Cursor.Clip = new System.Drawing.Rectangle()
        ...