Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Using Win32 in Unity

Discussion in 'Scripting' started by ToshoDaimos, Mar 22, 2018.

  1. ToshoDaimos

    ToshoDaimos

    Joined:
    Jan 30, 2013
    Posts:
    679
    I would like to use GetCursorPos() from User32.dll on Windows in my Unity project. The problem is that its full signature is "BOOL WINAPI GetCursorPos(LPPOINT lpPoint);". I don't know how can I use that Point structure. Tell me how to use a native function which returns a struct using a pointer in Unity.
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    This is the code I have:
    Code (csharp):
    1. #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
    2. public class Win32
    3. {
    4.     [DllImport("User32.Dll")]
    5.     public static extern long SetCursorPos(int x, int y);
    6.  
    7.     [DllImport("user32.dll")]
    8.     [return: MarshalAs(UnmanagedType.Bool)]
    9.     public static extern bool GetCursorPos(out POINT lpPoint);
    10.  
    11.     [StructLayout(LayoutKind.Sequential)]
    12.     public struct POINT
    13.     {
    14.         public int X;
    15.         public int Y;
    16.  
    17.         public POINT(int x, int y)
    18.         {
    19.             this.X = x;
    20.             this.Y = y;
    21.         }
    22.     }
    23. }
    24. #endif
    25.  
    26. // and some snippet using it...
    27. #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
    28.             Win32.POINT pt = new Win32.POINT();
    29.             Win32.GetCursorPos(out pt);
    30.             pos.x = pt.X;
    31.             pos.y = pt.Y;
    32. #endif
     
    ToshoDaimos likes this.
  3. ToshoDaimos

    ToshoDaimos

    Joined:
    Jan 30, 2013
    Posts:
    679
    That's exactly what I needed! Thanks! :)
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You're welcome. I remember being very happy when I found it, too =)
     
  5. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    Just out of curiosity: What is wrong with Unity's built-in Cursor functionality?
     
  6. ToshoDaimos

    ToshoDaimos

    Joined:
    Jan 30, 2013
    Posts:
    679
    For ex. there is no way to lock cursor in place.
     
  7. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Well, I think you can only lock it in the middle? :)

    I use the posted 2 methods so that I can hide the cursor while moving the camera (while the left, right or both mouse buttons are down), and I store the cursor's position and restore it afterwards. While the camera is moving the cursor is locked so it doesn't go out of the window.

    It's a small thing, but I really like the functionality, as it matched a game I had played for a long time.