Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
6
Question by Anthias · Oct 28, 2013 at 09:09 AM · cursorkeyboard

How can I control the mouse (Move and send mouse click signals) via the keyboard?

Hi all, in my game I want move the mouse cursor in the screen, with the keyboard arrows for example, and I want "click" with an another keyboard key. So without use my mouse. Is it possible (of course with use script)? How can I do this?

Thank you

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
14
Best Answer

Answer by vexe · Oct 28, 2013 at 09:27 AM

So you want to move the mouse, with your keyboard, something like:

 if (left arrow pressed)
    mouse.x -= value;
 else if (right arrow pressed)
    mouse.x += value;
 else if etc

Last time I tried and searched how would I do this, how would I set the mouse cursor coordinates, I failed to find a Unity-way of doing this. Since, setting the system mouse coords, needs actual communication to the operating system, and since each operating system does it in its own way, there isn't one unified way of doing this. But I don't know why didn't Unity do something like:

 public void SetMouse(float x, float y)
 {
     if (OS is Windows)
       doItOne();
     else if (OS is Mac)
       doItTwo();
     else if etc
 }

And then just provide us a common interface we could deal with, so we don't have to worry about which OS we're dealing with, it takes care of it.

ANYWAY, if you're on Windows, you could use some WindowsAPIs to set the coords, like seen in my inventory video (6:30) where I locked the mouse in the bag area.

To get the mouse, you could use GetCursorPos, to set it, SetCursorPos.

First:

 using System.Runtime.InteropServices;

Then you need to import the functions:

 [DllImport("user32.dll")]
 public static extern bool SetCursorPos(int X, int Y);
 [DllImport("user32.dll")]
 public static extern bool GetCursorPos(out Point pos);

Usage:

First, you need to create a Point struct, see. Then you could:

 Point cursorPos = new Point();
 GetCursorPos(out cursorPos);

And:

 SetCursorPos(x, y);

It's good to note that the 0,0 point of the screen for Windows is the top left when you're working with Get/SetCursor. MSDN

EDIT: To send a mouse click from a keyboard button, first go to this link and copy-paste the code in the SECOND answer somewhere (exclude anything you don't need/already have)

Then, to use it:

 public class Test : MonoBehaviour
 {
     void OnGUI()
     {
         if (GUI.Button(new Rect(10, 10, 100, 100), "BUTTON"))
             Debug.Log("clicked button");
     }
     void Update()
     {
         if (Input.GetKeyDown(KeyCode.Space))
             MouseOperations.MouseEvent(MouseOperations.MouseEventFlags.LeftUp | MouseOperations.MouseEventFlags.LeftDown);
     }
 }

This will send out a LeftDown and LeftUp signals. If you just do a LeftDown, it's like holding the left mouse button down, so you won't get a complete click.

Test this code out, attach it to some gameObject, place your mouse on the button, and when you press "Space" it will send a left click as if you clicked on the button, cool huh? :D

Comment
Add comment · Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Anthias · Oct 28, 2013 at 10:38 AM 0
Share

Perfect! $$anonymous$$y code work, and I can move my mouse cursor with the keyboard. So, now, how I can "click" with a keyboard key too?

avatar image vexe · Oct 28, 2013 at 12:01 PM 1
Share

Updated, take a look.

avatar image Jamora · Oct 28, 2013 at 12:10 PM 4
Share

Unity does have platform dependent compilation, so you can have the functionality in

 if (OS is Windows)
     doItOne();
 else if (OS is $$anonymous$$ac)
     doItTwo();
 else if etc

by writing

 #if UNITY_STANDALONE_WIN
     doItOne();
 #endif
 #if UNITY_STANDALONE_OSX
     doItTwo();
 #endif
 


avatar image vexe · Oct 28, 2013 at 12:13 PM 3
Share

Then why the hell won't Unity provide us a unified way to set/get the mouse coords??? I don't get how they think!

avatar image Jamora · Oct 28, 2013 at 01:02 PM 0
Share

That's a good question. $$anonymous$$aybe no one has asked for one. $$anonymous$$aybe something will break internally if the mouse position is changed from code. Who knows.

Show more comments
avatar image
4

Answer by alvaro-em · Jun 09, 2014 at 11:09 AM

Just in case someone is looking for the Mac approach, here is a fast working approximation (not refined). Hope it helps:

 if UNITY_STANDALONE_OSX
 
     public enum _CGEventType 
     {
         kCGEventLeftMouseDown       = 1,
         kCGEventLeftMouseUp         = 2,
         kCGEventRightMouseDown      = 3,
         kCGEventRightMouseUp        = 4,
         kCGEventMouseMoved          = 5,
         kCGEventLeftMouseDragged    = 6,
         kCGEventRightMouseDragged   = 7,
         kCGEventKeyDown             = 10,
         kCGEventKeyUp               = 11,
         kCGEventFlagsChanged        = 12,
         kCGEventScrollWheel         = 22,
         kCGEventTabletPointer       = 23,
         kCGEventTabletProximity     = 24,
         kCGEventOtherMouseDown      = 25,
         kCGEventOtherMouseUp        = 26,
         kCGEventOtherMouseDragged   = 27
 //        kCGEventTapDisabledByTimeout = 0xFFFFFFFE,
 //        kCGEventTapDisabledByUserInput = 0xFFFFFFFF
     };
     
     public enum _CGMouseButton {
         kCGMouseButtonLeft = 0,
         kCGMouseButtonRight = 1,
         kCGMouseButtonCenter = 2
     };
     
     public struct CGPoint
     {
         float x;
         float y;
 
         public CGPoint(float x, float y)
         {
             this.x = x;
             this.y = y;
         }
 
         public override string ToString ()
         {
             return string.Format ("["+x+","+y+"]");
         }
     }
 
     [DllImport("/System/Library/Frameworks/Quartz.framework/Versions/Current/Quartz")]
     private static extern uint CGEventCreateMouseEvent( int? source, _CGEventType mouseType, CGPoint mouseCursorPosition, _CGMouseButton mouseButton);
 
     public static void MouseEvent(_CGEventType eventType, CGPoint position)
     {    
         CGEventCreateMouseEvent((int?)null, _CGEventType.kCGEventLeftMouseDown, position, _CGMouseButton.kCGMouseButtonLeft);
 
     }
     
 #endif
 
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

20 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Lock the screen 1 Answer

Moving the keyboard cursor position to the end of a TextField 6 Answers

Editable text field in Android with cursor 0 Answers

OnGUI() and key pressing problems. 2 Answers

How can the iPad keyboard be properly landscaped? It always defaults to portrait 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges