private void Form1_Load(object sender, EventArgs e)
        {
            // Initialize DirectInput
            var directInput = new DirectInput();
            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Keyboard, DeviceEnumerationFlags.AllDevices))
                {
                controllers.Add(deviceInstance.InstanceGuid);
                comboBox1.Items.Add(deviceInstance.ProductName);
                }

            //controllers.Add(directInput.GetDevices(DeviceType.Keyboard, DeviceEnumerationFlags.AllDevices));
            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                {
                controllers.Add(deviceInstance.InstanceGuid);
                comboBox1.Items.Add(deviceInstance.ProductName);
                }

            // If Joystick not found, throws an error
            if (controllers.Count < 1)
                {
                if (MessageBox.Show("No Joystick or Keyboard has been found please try again\nProgram now will exit !", "No Controller Found", MessageBoxButtons.OK) == DialogResult.OK)
                    Application.Exit();

                }
        }
        private static void StartJoystickCapture(CancellationToken token)
        {
            var joystickGuid = Guid.Empty;
            var di = new DirectInput();
            foreach (var device in di.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AttachedOnly))
            {
                joystickGuid = device.InstanceGuid;
                break;
            }
            _joystick = new SharpDX.DirectInput.Joystick(di, joystickGuid);
            _joystick.Acquire();
            _currentThrottle = 0;
            _currentYawTrim = 0;
            while (!token.IsCancellationRequested)
            {
                var state = _joystick.GetCurrentState();

                _currentThrottle = (1000 - GetAnalogStickValue(state.Sliders[0])) / 2;
                Helicopter.Command.MainThrottle = _currentThrottle;

                Helicopter.Command.Pitch = GetAnalogStickValue(state.Y);

                //Helicopter.Command.Yaw = -1 * (GetAnalogStickValue(state.X) + _currentYawTrim); //For n64 controller
                Helicopter.Command.Yaw = -1 * (GetAnalogStickValue(state.RotationZ) + _currentYawTrim);

                var yawtrimChange = GetYawTrimChange(state.Buttons);
                _currentYawTrim += yawtrimChange;
                Helicopter.Command.YawTrim = _currentYawTrim;

                SetConsoleDisplay(state);
                Thread.Sleep(Speed);
            }
        }
Example #3
1
        private static void RunManager(InputConfig config)
        {
            try
            {
                var input = new DirectInput();
                var devices = new List<DeviceInstance>(input.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices));
                devices.AddRange(input.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices));

                var registeredDevices = new List<Tuple<Config.Input, Joystick>>();

                foreach (var inp in config.Inputs)
                {
                    var device = devices.SingleOrDefault(di => di.ProductGuid == new Guid(inp.Guid));
                    if (device == null)
                    {
                        throw new Exception($"Device \"{inp.Nickname}\" not found");
                    }

                    var joy = new Joystick(input, device.InstanceGuid);

                    registeredDevices.Add(Tuple.Create(inp, joy));
                }

                while (true)
                {
                    var frame = new InputFrame();
                    frame.GenerationTime = DateTime.Now;

                    foreach (var registeredDevice in registeredDevices)
                    {
                        var state = registeredDevice.Item2.GetCurrentState();

                        switch (registeredDevice.Item1.Type.ToUpper())
                        {
                            case "JOYSTICK":
                                frame.SubFrames.Add(new JoystickSubFrame(state));
                                break;
                            case "GAMEPAD":
                                frame.SubFrames.Add(new GamepadSubFrame(state));
                                break;
                        }
                    }

                    FrameCaptured?.Invoke(frame);
                }

            }
            catch (ThreadAbortException)
            {
                Console.Error.WriteLine("Input Manager Stopped at " + DateTime.Now.ToString("G"));
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error: {ex.Message}\n\nInput Manager cannot continue", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }
        private static void HandleJoystick()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                        DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                        DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Debug.WriteLine("No Gamepad found.");
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Debug.WriteLine("Found Gamepad with GUID: {0}", joystickGuid);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            // Poll events from joystick every 1 millisecond
            var timer = Observable.Interval(TimeSpan.FromMilliseconds(1));

            timer
                // Get all joystick input
                .SelectMany(_ => { joystick.Poll(); return joystick.GetBufferedData(); })
                // Filter only menu key button (xbox one controller)
                .Where(a => a.Offset == JoystickOffset.Buttons6)
                // Input will contain UP and Down button events
                .Buffer(2)
                // If button was pressed longer than a second
                .Where(t => (TimeSpan.FromMilliseconds(t.Last().Timestamp) - TimeSpan.FromMilliseconds(t.First().Timestamp)).TotalSeconds >= 1)
                // Press and hold F key for 1.5s
                .Subscribe(t =>
                {
                    SendKeyDown(KeyCode.KEY_F);
                    System.Threading.Thread.Sleep(1500);
                    SendKeyUp(KeyCode.KEY_F);
                });
        }
		private void ConfigEditDialog_Load(object sender, EventArgs e)
		{
			directInput = new DirectInput();
            var list = directInput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly);
            if (list.Count > 0)
            {
                inputDevice = new Joystick(directInput, list.First().InstanceGuid);
                tableLayoutPanel1.RowCount = actionNames.Length;
                for (int i = 0; i < actionNames.Length; i++)
                {
                    tableLayoutPanel1.Controls.Add(new Label() 
                    {
                        AutoSize = true,
                        Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Top,
                        Text = actionNames[i],
                        TextAlign = ContentAlignment.MiddleLeft
                    }, 0, i);
                    ButtonControl buttonControl = new ButtonControl() { Enabled = false };
                    tableLayoutPanel1.Controls.Add(buttonControl, 1, i);
                    buttonControls.Add(buttonControl);
                    buttonControl.SetButtonClicked += buttonControl_SetButtonClicked;
                    buttonControl.ClearButtonClicked += buttonControl_ClearButtonClicked;
                    if (i == tableLayoutPanel1.RowStyles.Count)
                        tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
                }
            }
            else
                tabControl1.TabPages.Remove(tabPage_Controller);
            // Load the config INI upon window load
			LoadConfigIni();
		}
Example #6
1
        //Disable all dinput devices for xinput controllers
        public void Lock_DX_Devices()
        {
            var directInput = new DirectInput();

            try
            {
                IList<DeviceInstance> devicelist = directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AttachedOnly);

                foreach (DeviceInstance cdevice in devicelist)
                {
                    if (cdevice.InstanceName.Trim('\0') == XINPUT_NAME)
                    {
                        var joystick = new Joystick(directInput, cdevice.InstanceGuid);
                        joystick.Acquire();
                        Guid deviceGUID = joystick.Properties.ClassGuid;
                        string devicePath = joystick.Properties.InterfacePath;
                        joystick.Unacquire();
                        string[] dpstlit = devicePath.Split('#');
                        devicePath = @"HID\" + dpstlit[1].ToUpper() + @"\" + dpstlit[2].ToUpper();
                        lockedDevices.Add(new DeviceID(deviceGUID, devicePath));

                        DeviceHelper.SetDeviceEnabled(deviceGUID, devicePath, false);
                    }
                }
            }
            finally
            {
                directInput.Dispose();
            }
        }
Example #7
0
        /// <inheritdoc/>
        public IEnumerable <ILowLevelInputDevice> GetAllDevices()
        {
            var directInput = new SharpDX.DirectInput.DirectInput();
            var devices     = directInput.GetDevices(DeviceClass.All, DeviceEnumerationFlags.AttachedOnly);

            var directInputGamepads =
                this.GetGenericGamepads(devices.Where(device => device.Type == SharpDX.DirectInput.DeviceType.Gamepad ||
                                                      device.Type == SharpDX.DirectInput.DeviceType
                                                      .Joystick), directInput);
            var xinputGamepads = this.GetXInputGamepads();
            var keyboards      = directInput.GetDevices(DeviceClass.Keyboard, DeviceEnumerationFlags.AllDevices)
                                 .Select(keyboard => new LowLevelInputDevice()
            {
                DiscoveryApi    = InputApi.DirectInput,
                DI_InstanceGUID = keyboard.InstanceGuid,
                DI_InstanceName = keyboard.InstanceName.Trim('\0'),
                DI_ProductName  = keyboard.ProductName.Trim('\0'),
                DI_ProductGUID  = keyboard.ProductGuid,
                DI_DeviceType   = DeviceType.Keyboard,
            });

            var mice = directInput.GetDevices(DeviceClass.Pointer,
                                              DeviceEnumerationFlags.AllDevices).Select(mouse => new LowLevelInputDevice()
            {
                DiscoveryApi    = InputApi.DirectInput,
                DI_InstanceGUID = mouse.InstanceGuid,
                DI_InstanceName = mouse.InstanceName.Trim('\0'),
                DI_ProductName  = mouse.ProductName.Trim('\0'),
                DI_ProductGUID  = mouse.ProductGuid,
                DI_DeviceType   = DeviceType.Mouse,
            });

            return(directInputGamepads.Concat(xinputGamepads).Concat(keyboards).Concat(mice));
        }
Example #8
0
        public Gamepad()
        {
            dInput = new DI.DirectInput();
            var list = dInput.GetDevices(DI.DeviceType.Gamepad, DI.DeviceEnumerationFlags.AttachedOnly);

            if (list.Count == 0)
            {
                list = dInput.GetDevices(DI.DeviceType.Joystick, DI.DeviceEnumerationFlags.AttachedOnly);
                if (list.Count == 0)
                {
                    padConnected = false;
                }
                else
                {
                    padConnected = true;
                }
            }
            else
            {
                padConnected = true;
            }

            if (padConnected)
            {
                padTrans = new bool[8];
                Pad      = new DI.Joystick(dInput, list[0].InstanceGuid);
                //Pad.Acquire();
            }
        }
Example #9
0
        public Controller()
        {
            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                MessageBox.Show("No joystick/Gamepad found.");
            }
            else
            {
                value    = 0;
                joystick = new Joystick(directInput, joystickGuid);
                // Set BufferSize in order to use buffered data.
                joystick.Properties.BufferSize = 128;
                // Acquire the joystick
                joystick.Acquire();
            }
        }
Example #10
0
        public GamePad()
        {
            // Initialize DirectInput
            directInput = new DirectInput();

            // Find a Joystick Guid
            joystickGuid = Guid.Empty;

            // Find a Gamepad
            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                        DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                        DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Logger.Log(this, "No joystick/Gamepad found.", 2);            
            }
            else
            {
                // Instantiate the joystick
                joystick = new Joystick(directInput, joystickGuid);

                Logger.Log(this, String.Format("Found Joystick/Gamepad with GUID: {0}", joystickGuid), 1);

                // Set BufferSize in order to use buffered data.
                joystick.Properties.BufferSize = 128;

                // Acquire the joystick
                joystick.Acquire();

                // Poll events from joystick


                //while (true)
                //{
                //    joystick.Poll();
                //    var datas = joystick.GetBufferedData();
                //    foreach (var state in datas)
                //        Console.WriteLine(state);
                //}

                timer = new Timer();
                timer.Interval = TIMER_INTERVAL_IN_MS;
                timer.Tick += new EventHandler(timer_Tick);
                timer.Start();
            }
        }
Example #11
0
 /// <summary>
 /// Gets the current available DirectInput devices.
 /// </summary>
 /// <param name="allDevices">No filter</param>
 /// <returns>List of devices</returns>
 public IEnumerable <DeviceInstance> GetInputDevices(bool allDevices)
 {
     if (allDevices)
     {
         return(directInput.GetDevices().Where(di => di.Type != DeviceType.Keyboard));
     }
     else
     {
         return(directInput.GetDevices().Where(di => di.Type == DeviceType.Joystick || di.Type == DeviceType.Gamepad || di.Type == DeviceType.FirstPerson));
     }
 }
Example #12
0
        static void MainForJoystick()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();
            foreach (var effectInfo in allEffects)
                Console.WriteLine("Effect available {0}", effectInfo.Name);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            // Poll events from joystick
            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                    Console.WriteLine(state);
            }
        }
Example #13
0
        public void ObtainJoystick()
        {
            if (DJoystick != null) {
                DJoystick.Dispose();
            }

            directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices)) {
                joystickGuid = deviceInstance.InstanceGuid;
            }

            if (joystickGuid == Guid.Empty) {
                Log.LogMessage("No joystick connected");
                return;
            }

            // Instantiate the joystick
            DJoystick = new DirectJoystick(directInput, joystickGuid);

            Log.LogMessage("Found Joystick with GUID: {0}		Name: {1}", joystickGuid, DJoystick.Information.ProductName);

            // Set BufferSize in order to use buffered data.
            DJoystick.Properties.BufferSize = 128;

            // Acquire the joystick
            DJoystick.Acquire();
        }
Example #14
0
        private List <DeviceInstance> GetDevices()
        {
            List <DeviceInstance> devices = new List <DeviceInstance>();

            try
            {
                foreach (DeviceType deviceType in DEVICE_TYPES)
                {
                    IList <DeviceInstance> foundDevices = directInput.GetDevices(deviceType, DeviceEnumerationFlags.AllDevices);

                    foreach (DeviceInstance device in foundDevices)
                    {
                        devices.Add(device);
                    }
                }
            }
            catch (SharpDXException dxException)
            {
                EventBus <SharpDXException> .Instance.SendEvent(this, dxException);

                Logger.Error("SharpDXException while getting DirectX devices: ", dxException);
            }

            return(devices);
        }
Example #15
0
        static void Main(string[] args)
        {
            // Initialize DirectInput
            var  dirInput      = new SharpDX.DirectInput.DirectInput();
            var  typeJoystick  = SharpDX.DirectInput.DeviceType.Gamepad;
            var  allDevices    = dirInput.GetDevices();
            bool isGetJoystick = false;

            foreach (var item in allDevices)
            {
                if (typeJoystick == item.Type)
                {
                    curJoystick = new SharpDX.DirectInput.Joystick(dirInput, item.InstanceGuid);
                    curJoystick.Acquire();
                    isGetJoystick = true;
                    Thread t1 = new Thread(joyListening);
                    t1.IsBackground = true;
                    t1.Start();
                }
            }
            if (!isGetJoystick)
            {
                Console.WriteLine("没有插入手柄");
                Console.WriteLine("Press any key to exit!");
            }
            Console.ReadKey();
        }
Example #16
0
        public Manual()
        {
            // Initialize DirectInput

            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                        DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                        DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            if (joystickGuid != Guid.Empty)
            {
                //fix running code without controller
                //Environment.Exit(1);

                // Instantiate the joystick
                joystick = new Joystick(directInput, joystickGuid);

                Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

                // Query all suported ForceFeedback effects
                var allEffects = joystick.GetEffects();
                foreach (var effectInfo in allEffects)
                    Console.WriteLine("Effect available {0}", effectInfo.Name);

                // Set BufferSize in order to use buffered data.
                joystick.Properties.BufferSize = 128;

                // Acquire the joystick
                joystick.Acquire();
                ControllerOn = true;
            }
        }
Example #17
0
        public GamepadHook()
        {
            var input = new DirectInput();
            var devices = input.GetDevices();
            Joysticks = devices
                .Where(x => x.Type != DeviceType.Keyboard)
                .Select(x => new Joystick(input, x.InstanceGuid)).ToList();

            foreach (var joystick in Joysticks)
            {
                joystick.Properties.BufferSize = 128;
                joystick.Acquire();
            }
        }
Example #18
0
        private Keyboard StartKeyboard()
        {
            var      dirInput   = new SharpDX.DirectInput.DirectInput();
            var      allDevices = dirInput.GetDevices();
            Keyboard keyboard   = null;

            foreach (var item in allDevices)
            {
                if (SharpDX.DirectInput.DeviceType.Keyboard == item.Type)
                {
                    keyboard = new SharpDX.DirectInput.Keyboard(dirInput);
                    keyboard.Acquire();
                }
            }
            return(keyboard);
        }
        public Joystick checkDevices()
        {
            SharpDX.DirectInput.DirectInput directInput = new SharpDX.DirectInput.DirectInput();

            var devices = directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AttachedOnly);

            Console.WriteLine("Wykryłem następujące urządzenia:");
            foreach (DeviceInstance instance in devices)
            {
                Console.WriteLine(instance.InstanceName);
            }

            Joystick joystick = new Joystick(directInput, devices[0].InstanceGuid);

            return(joystick);
        }
Example #20
0
 public void SearchDevices()
 {
     lock (lockObject)
     {
         IEnumerable <DeviceInstance> instances = directInput.GetDevices();
         if (allDevices)
         {
             instances = instances.Where(di => di.Type != DeviceType.Keyboard && di.Type != DeviceType.Mouse).ToList();
         }
         else
         {
             instances = instances.Where(di => di.Type == DeviceType.Joystick || di.Type == DeviceType.Gamepad || di.Type == DeviceType.FirstPerson).ToList();
         }
         List <string> uniqueIds = new List <string>();
         foreach (var instance in instances)
         {
             string instanceGuid = instance.InstanceGuid.ToString();
             string productGuid  = instance.ProductGuid.ToString();
             if (productGuid != EmulatedSCPID)
             {
                 var device = CreateDevice(instance, uniqueIds);
                 if (device == null)
                 {
                     continue;
                 }
                 var config = inputConfigManager.LoadConfig(device);
                 device.InputConfiguration = config;
                 if (config.Autostart)
                 {
                     device.Start();
                 }
                 currentDevices.Add(device);
                 Connected?.Invoke(this, new DeviceConnectedEventArgs(device));
             }
         }
         foreach (var device in currentDevices.ToArray())
         {
             if (!uniqueIds.Any(i => i == device.UniqueId))
             {
                 currentDevices.Remove(device);
                 device.Dispose();
                 Disconnected?.Invoke(this, new DeviceDisconnectedEventArgs(device));
             }
         }
     }
 }
 public void SearchDevices()
 {
     lock (lockObject)
     {
         IEnumerable <DeviceInstance> instances = directInput.GetDevices();
         if (allDevices)
         {
             instances = instances.Where(di => di.Type != DeviceType.Keyboard && di.Type != DeviceType.Mouse).ToList();
         }
         else
         {
             instances = instances.Where(di => di.Type == DeviceType.Joystick || di.Type == DeviceType.Gamepad || di.Type == DeviceType.FirstPerson).ToList();
         }
         foreach (var instance in instances)
         {
             string instanceGuid = instance.InstanceGuid.ToString();
             string productGuid  = instance.ProductGuid.ToString();
             if (!ignoredDeviceService.IsIgnored(productGuid, instanceGuid) && !currentDevices.Any(d => d.UniqueId == instanceGuid))
             {
                 var device = CreateDevice(instance);
                 if (device == null)
                 {
                     continue;
                 }
                 if (currentDevices.Any(d => d.UniqueId == device.UniqueId))
                 {
                     notificationService.Add(Notifications.DirectInputInstanceIdDuplication, new[] { device.UniqueId }, NotificationTypes.Warning);
                 }
                 var config = inputConfigManager.LoadConfig(device.UniqueId);
                 device.InputConfiguration = config;
                 currentDevices.Add(device);
                 Connected?.Invoke(this, new DeviceConnectedEventArgs(device));
             }
         }
         foreach (var device in currentDevices.ToArray())
         {
             string guid = device.UniqueId;
             if (!instances.Any(i => i.InstanceGuid.ToString() == guid))
             {
                 currentDevices.Remove(device);
                 device.Dispose();
                 Disconnected?.Invoke(this, new DeviceDisconnectedEventArgs(device));
             }
         }
     }
 }
Example #22
0
        public Input(Game game, IntPtr handle)
            : base(game, -10000)
        {
            _directInput = new DirectInput();
            _keyboard = new Keyboard(_directInput);
            _keyboard.Properties.BufferSize = 256;
            _keyboard.SetCooperativeLevel(handle, CooperativeLevel.Background | CooperativeLevel.NonExclusive);
            _mouse = new Mouse(_directInput);
            _mouse.Properties.AxisMode = DeviceAxisMode.Relative;
            _mouse.SetCooperativeLevel(handle, CooperativeLevel.Background | CooperativeLevel.NonExclusive);

            var devices  = _directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices);
            if (devices.Count > 0)
            {
                _joystick = new Joystick(_directInput, devices[0].InstanceGuid);
                _joystick.SetCooperativeLevel(handle, CooperativeLevel.Background | CooperativeLevel.NonExclusive);
            }
        }
Example #23
0
 public string[] FindJoysticks()
 {
     var ret = new string[]{};
     try
     {
         var dinput = new DirectInput();
         var r = dinput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly);
         if (r != null)
         {
             ret = r.Select(device => device.InstanceName + "|" + device.InstanceGuid.ToString()).ToArray();
         }                
     }
     catch (Exception ex)
     {
         Logger.LogExceptionToFile(ex);
     }
     return ret;
 }
Example #24
0
        public LedWizEngine()
        {
            var directInput            = new SharpDX.DirectInput.DirectInput();
            var joystickDeviceInstance = directInput.GetDevices().FirstOrDefault(x => x.Type == SharpDX.DirectInput.DeviceType.Joystick);//FIX THIS to be more specific! currently it'll take the first joystick it finds... this is dumb.

            if (joystickDeviceInstance == null)
            {
                throw new LedWizDeviceNotFoundException();
            }
            _joystick = new SharpDX.DirectInput.Joystick(directInput, joystickDeviceInstance.InstanceGuid);
            _joystick.Properties.BufferSize = 128;

            _hardwarePoller.WorkerSupportsCancellation = true;
            _hardwarePoller.WorkerReportsProgress      = false;
            _hardwarePoller.DoWork             += _hardwarePoller_DoWork;
            _hardwarePoller.RunWorkerCompleted += _hardwarePoller_RunWorkerCompleted;

            _ledWiz = new LEDWiz(IntPtr.Zero);
            _ledWiz.StartupLighting();
        }
        /// <summary>
        /// Acquires, finds and evaluates all of the currently available joysticks. keyboards and
        /// other valid input devices.
        /// </summary>
        private void GetConnectedControllers()
        {
            // Instantiate the DirectInput adapter.
            _directInputAdapter = new SharpDX.DirectInput.DirectInput();

            // Allocate a list of controllers.
            _dInputControllers = new List <DInputController>();

            // Allocate a list of device instances.
            List <DeviceInstance> dInputDevices = new List <DeviceInstance>();

            // Acquire all DInput devices.
            dInputDevices.AddRange(_directInputAdapter.GetDevices(DeviceClass.All, DeviceEnumerationFlags.AttachedOnly));

            // Acquire and initialize each device.
            foreach (DeviceInstance dInputDevice in dInputDevices)
            {
                // Filter devices to initialize by type.
                if (dInputDevice.Type == DeviceType.Joystick)
                {
                    _dInputControllers.Add(SetupController(dInputDevice));
                }

                else if (dInputDevice.Type == DeviceType.Gamepad)
                {
                    _dInputControllers.Add(SetupController(dInputDevice));
                }

                else if (dInputDevice.Type == DeviceType.Keyboard)
                {
                    _dInputControllers.Add(SetupController(dInputDevice));
                }

                else if (dInputDevice.Type == DeviceType.Mouse)
                {
                    _dInputControllers.Add(SetupController(dInputDevice));
                }
            }
        }
Example #26
0
        public IInputSource CreateInputSource(InputType inputType)
        {
            switch (inputType)
            {
            case InputType.Keyboard:
                return(new DirectInputKeyboard(_nativeDirectInput));

            case InputType.MouseMovement:
                return(new DirectInputMouse(_nativeDirectInput));

            case InputType.Joystick:
                var gameDevice = _nativeDirectInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AttachedOnly).FirstOrDefault();
                if (gameDevice != null)
                {
                    return(new DirectInputJoystick(_nativeDirectInput, gameDevice.ProductGuid));
                }
                throw new Exception("No attached joystick found.");

            default:
                throw new ArgumentOutOfRangeException(nameof(inputType), inputType, null);
            }
        }
Example #27
0
        public GamepadHook()
        {
            var input = new DirectInput();
            var devices = input.GetDevices();
            Joysticks = devices
                .Where(x => x.Type != DeviceType.Keyboard)
                .Select(x => new Joystick(input, x.InstanceGuid)).ToList();

            for (var ind = 0; ind < Joysticks.Count; ind++)
            {
                var joystick = Joysticks[ind];
                try
                {
                    joystick.Properties.BufferSize = 128;
                    joystick.Acquire();
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    Joysticks.RemoveAt(ind);
                    ind--;
                }
            }
        }
Example #28
0
        public void ThreadStart()
        {
            byte[] keybdState = new byte[256];
            GetKeyboardState(keybdState);

            NumLock    = (keybdState[(int)VK.VK_NUMLOCK] & 1) != 0;
            CapsLock   = (keybdState[(int)VK.VK_CAPITAL] & 1) != 0;
            ScrollLock = (keybdState[(int)VK.VK_SCROLL] & 1) != 0;

            Shift  = (keybdState[(int)VK.VK_SHIFT] & 0x80) != 0;
            LShift = (keybdState[(int)VK.VK_LSHIFT] & 0x80) != 0;
            RShift = (keybdState[(int)VK.VK_RSHIFT] & 0x80) != 0;

            Ctrl  = (keybdState[(int)VK.VK_CONTROL] & 0x80) != 0;
            LCtrl = (keybdState[(int)VK.VK_LCONTROL] & 0x80) != 0;
            RCtrl = (keybdState[(int)VK.VK_RCONTROL] & 0x80) != 0;

            Alt  = (keybdState[(int)VK.VK_MENU] & 0x80) != 0;
            LAlt = (keybdState[(int)VK.VK_LMENU] & 0x80) != 0;
            RAlt = (keybdState[(int)VK.VK_RMENU] & 0x80) != 0;

            var directInput = new SharpDX.DirectInput.DirectInput();

            var keybdGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Keyboard, DeviceEnumerationFlags.AllDevices))
            {
                keybdGuid = deviceInstance.InstanceGuid;
            }

            if (keybdGuid == Guid.Empty)
            {
                Environment.Exit(1);
            }

            var keybd = new SharpDX.DirectInput.Keyboard(directInput);

            keybd.Properties.BufferSize = 128;
            keybd.Acquire();

            string         keys             = "";
            VK             vk               = 0x00;
            KeyboardUpdate Scan             = new KeyboardUpdate();
            Stopwatch      holdInSW         = new Stopwatch();
            Stopwatch      holdInIntervalSW = new Stopwatch();

            holdInSW.Start();
            holdInIntervalSW.Start();

            var dwThread = Native.WinAPI.GetCurrentThreadId();

            while (true)
            {
                Thread.Sleep(1);
                Native.DesktopSwitch.PollAutoDesktopThreadSwitch(dwThread);
                keybd.Poll();
                var datas = keybd.GetBufferedData();

                if (datas.Length != 0)
                {
                    holdInSW.Restart();
                }
                else if (holdInSW.Elapsed > PressedInHoldTime && Scan.IsPressed)
                {
                    if (holdInIntervalSW.Elapsed > PressedInInterval)
                    {
                        HandleKey(keys, vk, Scan.Key, Scan.IsPressed);
                        holdInIntervalSW.Restart();
                    }
                }

                foreach (var state in datas)
                {
                    /*if (state.Key == Key.F12) {
                     *      Hooks.RemoveHooks();
                     *      Environment.Exit(0);
                     *      Debug.Assert(false);
                     *      var a = (1 + 9) - 10;
                     *      Debug.WriteLine((15 / a));
                     *      return;
                     * }*/
                    if (state.IsPressed)
                    {
                        switch (state.Key)
                        {
                        case Key.Capital:
                            CapsLock = !CapsLock;
                            break;

                        case Key.NumberLock:
                            NumLock = !NumLock;
                            break;

                        case Key.ScrollLock:
                            ScrollLock = !ScrollLock;
                            break;
                        }
                    }
                    switch (state.Key)
                    {
                    case Key.RightShift:
                        RShift = state.IsPressed;
                        break;

                    case Key.LeftShift:
                        LShift = state.IsPressed;
                        break;

                    case Key.LeftControl:
                        LCtrl = state.IsPressed;
                        break;

                    case Key.RightControl:
                        RCtrl = state.IsPressed;
                        break;

                    case Key.LeftAlt:
                        LAlt = state.IsPressed;
                        break;

                    case Key.RightAlt:
                        RAlt = state.IsPressed;
                        break;
                    }

                    Shift = LShift || RShift;
                    Ctrl  = LCtrl || RCtrl;
                    Alt   = LAlt || RAlt;

                    byte[] keyState = new byte[256];

                    if (CapsLock)
                    {
                        keyState[(int)VK.VK_CAPITAL] = 0x01;
                    }
                    if (NumLock)
                    {
                        keyState[(int)VK.VK_NUMLOCK] = 0x01;
                    }
                    if (ScrollLock)
                    {
                        keyState[(int)VK.VK_SCROLL] = 0x01;
                    }
                    if (Shift)
                    {
                        keyState[(int)VK.VK_SHIFT] = 0x80;
                    }
                    if (Ctrl)
                    {
                        keyState[(int)VK.VK_CONTROL] = 0x80;
                    }
                    if (Alt)
                    {
                        keyState[(int)VK.VK_MENU] = 0x80;
                    }

                    keys = ScancodeToUnicode(state.Key, keyState);
                    vk   = ScancodeToVKCode(state.Key);
                    Scan = state;

                    HandleKey(keys, vk, Scan.Key, Scan.IsPressed);
                }
            }
        }
Example #29
0
        /*
         * Init USB HID Transmitter and make connection
         */
        private void InitHIDTransmitter()
        {
            // Initialize DirectInput
            _directInput = new DirectInput();

            // Find Transmitter Guid
            var transmitterGuid = Guid.Empty;

            // Find Transmitter
            if (transmitterGuid == Guid.Empty)
                foreach (var deviceInstance in _directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                    transmitterGuid = deviceInstance.InstanceGuid;

            // If no device found, throw an error
            if (transmitterGuid == Guid.Empty)
            {
                Console.WriteLine("No HID device found.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Instantiate the joystick
            _HIDTransmitterInterface = new Joystick(_directInput, transmitterGuid);

            Console.WriteLine("Found HID Transmitter (as joystick) with GUID: {0}", transmitterGuid);

            // Set BufferSize in order to use buffered data.
            _HIDTransmitterInterface.Properties.BufferSize = 128;
            _HIDTransmitterInterface.Properties.Range = new InputRange(0, 255);

            // Acquire device
            _HIDTransmitterInterface.Acquire();

            _HIDControlsModel = new MessageModel();

            // create timeout for reseting positions if no detection in defined interval
            _timerID = Utils.SetTimer(HIDReadData, 1);
        }
Example #30
0
        /// <summary>
        /// Aquire the DInput joystick devices
        /// </summary>
        /// <returns></returns>
        public bool InitDirectInput( )
        {
            log.Debug( "Entry" );

              // Enumerate joysticks in the system.
              int tabs = 0;
              SharpDX.XInput.UserIndex gpDeviceIndex = SharpDX.XInput.UserIndex.Any;

              try {
            // Initialize DirectInput
            log.Debug( "Instantiate DirectInput" );
            var directInput = new DirectInput( );

            log.Debug( "Get Keyboard device" );
            m_Keyboard = new KeyboardCls( new Keyboard( directInput ), this );

            // scan the Input for attached devices
            log.Debug( "Scan GameControl devices" );
            int nJs = 1; // number the Joystick Tabs
            foreach ( DeviceInstance instance in directInput.GetDevices( DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly ) ) {

              log.InfoFormat( "GameControl: #{0} Type:{1} Device:{2}", tabs, instance.Type.ToString( ), instance.ProductName );
              // Create the device interface
              log.Debug( "Create the device interface" );
              SharpDX.DirectInput.Joystick jsDevice = null;
              SharpDX.XInput.Controller gpDevice = null;
              JoystickCls js = null; GamepadCls gs = null;
              if ( m_AppSettings.DetectGamepad && ( instance.Usage == SharpDX.Multimedia.UsageId.GenericGamepad ) ) {
            // detect Gamepad only if the user wishes to do so
            for ( SharpDX.XInput.UserIndex i =  SharpDX.XInput.UserIndex.One; i < SharpDX.XInput.UserIndex.Four; i++ ) {
              gpDevice = new SharpDX.XInput.Controller( i );
              if ( gpDevice.IsConnected ) {
                log.InfoFormat( "Scan Input {0} for gamepad - {1}", i, gpDevice.GetCapabilities( SharpDX.XInput.DeviceQueryType.Gamepad ).ToString( ) );
                gpDeviceIndex = i;
                break;
              }
            }
              }
              else {
            jsDevice = new Joystick( directInput, instance.InstanceGuid );
            log.DebugFormat( "Create the device interface for: {0}", jsDevice.Information.ProductName );
              }

              // we have the first tab made as reference so TabPage[0] already exists
              if ( tabs == 0 ) {
            // first panel - The Tab content exists already
            if ( gpDevice != null ) {
              log.Debug( "Add first Gamepad panel" );
              tc1.TabPages[tabs].Text = "Gamepad ";
              UC_GpadPanel uUC_GpadPanelNew = new UC_GpadPanel( ); tc1.TabPages[tabs].Controls.Add( uUC_GpadPanelNew );
              uUC_GpadPanelNew.Size = UC_JoyPanel.Size; uUC_GpadPanelNew.Location = UC_JoyPanel.Location;
              UC_JoyPanel.Enabled = false; UC_JoyPanel.Visible = false; // don't use this one
              log.Debug( "Create Gamepad instance" );
              gs = new GamepadCls( gpDevice, uUC_GpadPanelNew, tabs ); // does all device related activities for that particular item
              gs.SetDeviceName( instance.ProductName );
              tc1.TabPages[tabs].ToolTipText = String.Format( "{0}\n{1}", gs.DevName, " " );
              toolTip1.SetToolTip( tc1.TabPages[tabs], tc1.TabPages[tabs].ToolTipText );
            }
            else {
              log.Debug( "Add first Joystick panel" );
              log.Debug( "Create Joystick instance" );
              tc1.TabPages[tabs].Text = String.Format( "Joystick {0}", nJs++ );
              js = new JoystickCls( jsDevice, this, tabs + 1, UC_JoyPanel, tabs ); // does all device related activities for that particular item
              tc1.TabPages[tabs].ToolTipText = String.Format( "{0}\n{1}", js.DevName, js.DevInstanceGUID );
              toolTip1.SetToolTip( tc1.TabPages[tabs], tc1.TabPages[tabs].ToolTipText );
            }
              }
              else {
            if ( gpDevice != null ) {
              log.Debug( "Add next Gamepad panel" );
              tc1.TabPages.Add( "Gamepad " );
              UC_GpadPanel uUC_GpadPanelNew = new UC_GpadPanel( ); tc1.TabPages[tabs].Controls.Add( uUC_GpadPanelNew );
              uUC_GpadPanelNew.Size = UC_JoyPanel.Size; uUC_GpadPanelNew.Location = UC_JoyPanel.Location;
              log.Debug( "Create Gamepad instance" );
              gs = new GamepadCls( gpDevice, uUC_GpadPanelNew, tabs ); // does all device related activities for that particular item
              gs.SetDeviceName( instance.ProductName );
              tc1.TabPages[tabs].ToolTipText = String.Format( "{0}\n{1}", gs.DevName, " " );
              toolTip1.SetToolTip( tc1.TabPages[tabs], tc1.TabPages[tabs].ToolTipText );
            }
            else {
              log.Debug( "Add next Joystick panel" );
              // setup the further tab contents along the reference one in TabPage[0] (the control named UC_JoyPanel)
              tc1.TabPages.Add( String.Format( "Joystick {0}", nJs++ ) );
              UC_JoyPanel uUC_JoyPanelNew = new UC_JoyPanel( ); tc1.TabPages[tabs].Controls.Add( uUC_JoyPanelNew );
              uUC_JoyPanelNew.Size = UC_JoyPanel.Size; uUC_JoyPanelNew.Location = UC_JoyPanel.Location;
              log.Debug( "Create Joystick instance" );
              js = new JoystickCls( jsDevice, this, tabs + 1, uUC_JoyPanelNew, tabs ); // does all device related activities for that particular item
              tc1.TabPages[tabs].ToolTipText = String.Format( "{0}\n{1}", js.DevName, js.DevInstanceGUID );
              toolTip1.SetToolTip( tc1.TabPages[tabs], tc1.TabPages[tabs].ToolTipText );
            }
              }

              if ( gpDevice != null ) {
            m_Gamepad = gs;
            SetGamepadTab( tc1.TabPages[tabs] );  // indicates the gamepad tab (murks..)
            MyColors.GamepadColor = MyColors.TabColor[tabs]; // save it for future use
              }
              else if ( js != null ) {
            m_Joystick.Add( js ); // add to joystick list
            tc1.TabPages[tabs].Tag = ( m_Joystick.Count - 1 );  // used to find the tab for polling
              }
              tc1.TabPages[tabs].BackColor = MyColors.TabColor[tabs]; // each tab has its own color

              // next tab
              tabs++;
              if ( tabs >= JoystickCls.JSnum_MAX ) break; // cannot load more JSticks than predefined Tabs
            }
            log.DebugFormat( "Added {0} GameControl devices", tabs );

            if ( tabs == 0 ) {
              log.Warn( "Unable to find and/or create any joystick devices." );
              MessageBox.Show( "Unable to create a joystick device. Program will exit.", "No joystick found", MessageBoxButtons.OK, MessageBoxIcon.Information );
              return false;
            }

            // load the profile items from the XML
            log.Debug( "Init ActionTree" );
            InitActionTree( true );

              }
              catch ( Exception ex ) {
            log.Debug( "InitDirectInput failed unexpectedly", ex );
            return false;
              }

              return true;
        }
Example #31
0
        public bool AcquireJoystick(Guid guid)
        {
            try
            {
                if (_joystick != null)
                {
                    _joystick.Unacquire();
                    _joystick = null;
                }

                var dinput = new DirectInput();
                foreach (DeviceInstance device in dinput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly))
                {
                    if (device.InstanceGuid==guid)
                    {
                        _joystick = new SharpDX.DirectInput.Joystick(dinput, device.InstanceGuid);
                    }
                }

                if (_joystick != null)
                {
                    foreach (DeviceObjectInstance deviceObject in _joystick.GetObjects())
                    {

                        //if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0)
                        switch (deviceObject.ObjectId.Flags)
                        {
                            case DeviceObjectTypeFlags.Axis:
                            case DeviceObjectTypeFlags.AbsoluteAxis:
                            case DeviceObjectTypeFlags.RelativeAxis:
                                var ir = _joystick.GetObjectPropertiesById(deviceObject.ObjectId);
                                if (ir != null)
                                {
                                    try
                                    {
                                        ir.Range = new InputRange(-100, 100);
                                    }
                                    catch (Exception ex)
                                    {
                                        MainForm.LogExceptionToFile(ex);
                                    }
                                }
                                break;
                        }
                    }

                    _joystick.Acquire();

                    var cps = _joystick.Capabilities;
                    AxisCount = cps.AxeCount;

                    UpdateStatus();
                }
            }
            catch (Exception ex)
            {
                MainForm.LogExceptionToFile(ex);
                return false;
            }

            return true;
        }
        private void initializeController()
        {
            DirectInput directInput = new DirectInput();
            Guid joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No Gamepad found.");
            }

            controller = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Gamepad with GUID: {0}", joystickGuid);

            controller.Acquire();
        }
Example #33
0
        public bool Initialize(string instanceName)
        {
            bool bFoundDevice = false;

            // Initialize DirectInput
            DirectInput directInput = new DirectInput();

            // Find a Joystick Guid
            Guid joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
            {
                if (deviceInstance.InstanceName == instanceName)
                {
                    //found the device
                    joystickGuid = deviceInstance.InstanceGuid;
                }
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
            {
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                {
                    if (deviceInstance.InstanceName == instanceName)
                    {
                        joystickGuid = deviceInstance.InstanceGuid;
                    }
                }
            }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found: " + instanceName);
            }
            else
            {
                bFoundDevice = true;

                // Instantiate the joystick
                joystick = new Joystick(directInput, joystickGuid);

                Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

                // Query all suported ForceFeedback effects
                var allEffects = joystick.GetEffects();
                foreach (var effectInfo in allEffects)
                {
                    Console.WriteLine("Effect available {0}", effectInfo.Name);
                }

                // Set BufferSize in order to use buffered data.
                joystick.Properties.BufferSize = 128;

                // Acquire the joystick
                joystick.Acquire();
            }

            return bFoundDevice;
        }
Example #34
0
        static void Main(string[] args)
        {
            if (client == null)
            {
                // create client instance
                client = new MqttClient(IPAddress.Parse(MQTT_BROKER_ADDRESS));

                string clientId = Guid.NewGuid().ToString();
                client.Connect(clientId, "guest", "guest");

                SubscribeMessage();
            }
            // Initialize DirectInput

            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                        DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                        DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();
            foreach (var effectInfo in allEffects)
                Console.WriteLine("Effect available {0}", effectInfo.Name);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();
            const int stop = 32511;
            // Poll events from joystick
            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                {
                    if (state.Offset.ToString() == "X" && state.Value > stop)
                    {
                        MoveRobot("MOVE", "R");
                        Console.WriteLine("Kanan");
                    }
                    else if(state.Offset.ToString() == "X" && state.Value < stop)
                    {
                        MoveRobot("MOVE", "L");

                        Console.WriteLine("Kiri");
                    }
                    else if (state.Offset.ToString() == "Y" && state.Value < stop)
                    {
                        MoveRobot("MOVE", "F");

                        Console.WriteLine("Maju");
                    }
                    else if (state.Offset.ToString() == "Y" && state.Value > stop)
                    {
                        MoveRobot("MOVE", "B");

                        Console.WriteLine("Mundur");
                    }
                    else
                    {
                        MoveRobot("MOVE", "S");

                        Console.WriteLine("Stop");
                    }

                }

            }
        }
Example #35
0
        private void initialize_joystick()
        {
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                throw new Exception("controllerNotFound");
            }
            // Instantiate the joystick
            joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();
            foreach (var effectInfo in allEffects)
                Console.WriteLine("Effect available {0}", effectInfo.Name);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();
        }
Example #36
0
 static IList<DeviceInstance> GetDevices(DirectInput directInput)
 {
     return directInput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly);
 }
 private DeviceInstance GetJoystickInstance(DirectInput directInput)
 {
     var devices = directInput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly);
     if(devices.Count > 0)
     {
         return devices[0];
     }
     return null;
 }
Example #38
0
        static void MainForJoystick()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                Console.ReadKey();
                Environment.Exit(1);
            }
            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();
            foreach (var effectInfo in allEffects)
                Console.WriteLine("Effect available {0}", effectInfo.Name);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();
            string s = "there is a cat";
            string[] words = s.Split(' ');
            foreach (string word in words)
            {
                Console.WriteLine(word);
            }
            // Poll events from joystick
            var originX = 0;
            var originY = 0;
            var lastStateX = -1;
            var lastStateY = -1;
            var startFlag = false;
            while (true)
            {
                joystick.Poll();
                var datas = joystick.GetBufferedData();
                double theta = 0.0;
                double radius = 0.0;

                foreach (var state in datas)
                {
                    if (state.Sequence == 1)
                    {
                        s = (state.Offset).ToString();
                        if (s == "X")
                            originX = state.Value;
                        else if (s == "Y")
                            originY = state.Value;
                    }
                    s = (state.Offset).ToString();
                    if (s == "X")
                        lastStateX = state.Value;
                    else if (s == "Y")
                        lastStateY = state.Value;
                    startFlag = true;
                }
                if (startFlag && datas.Length == 0 && lastStateX != -1 && lastStateY != -1)
                {
                    var slope = 0.0;
                    if ((lastStateX - originX) == 0)
                        slope = Math.PI / 2;
                    else
                        slope = (lastStateY - originY) / (lastStateX - originX);
                    theta = Math.Atan(slope);
                    radius = Math.Sqrt(Math.Pow(originX - lastStateX, 2) + Math.Pow(originY - lastStateY, 2));
                    originX = lastStateX;
                    originY = lastStateY;
                    Console.WriteLine(theta);
                    Console.WriteLine(radius);
                    startFlag = false;
                }
            }
        }
Example #39
0
        public static int LoadControllers()
        {
            DirectInput dinput = new SharpDX.DirectInput.DirectInput();

            // Keyboard
            Controller kb = new Keyboard();

            controllers.Add(kb);
            Logcon(kb);

            // Mouse
            Controller mouse = new Mouse();

            controllers.Add(mouse);
            Logcon(mouse);

            // xbox360-like joystick
            foreach (DeviceInstance dinstance in dinput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AttachedOnly))
            {
                if (dinstance.InstanceGuid != Guid.Empty)
                {
                    Controller con = new Joystick(dinstance.InstanceGuid);
                    controllers.Add(con);
                    Logcon(con);
                }
            }
            // ps3-like joystick
            foreach (DeviceInstance dinstance in dinput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AttachedOnly))
            {
                if (dinstance.InstanceGuid != Guid.Empty)
                {
                    Controller con = new Joystick(dinstance.InstanceGuid);
                    controllers.Add(con);
                    Logcon(con);
                }
            }
            // Not implemented below
            foreach (DeviceInstance dinstance in dinput.GetDevices(DeviceType.Driving, DeviceEnumerationFlags.AttachedOnly))
            {
                if (dinstance.InstanceGuid != Guid.Empty)
                {
                    Controller con = new Joystick(dinstance.InstanceGuid);
                    controllers.Add(con);
                    Logcon(con);
                }
            }
            foreach (DeviceInstance dinstance in dinput.GetDevices(DeviceType.FirstPerson, DeviceEnumerationFlags.AttachedOnly))
            {
                if (dinstance.InstanceGuid != Guid.Empty)
                {
                    Controller con = new Joystick(dinstance.InstanceGuid);
                    controllers.Add(con);
                    Logcon(con);
                }
            }
            foreach (DeviceInstance dinstance in dinput.GetDevices(DeviceType.Flight, DeviceEnumerationFlags.AttachedOnly))
            {
                if (dinstance.InstanceGuid != Guid.Empty)
                {
                    Controller con = new Joystick(dinstance.InstanceGuid);
                    controllers.Add(con);
                    Logcon(con);
                }
            }

            for (int i = 0; i < Sanford.Multimedia.Midi.InputDevice.DeviceCount; i++)
            {
                Controller con = new MIDI(i);
                controllers.Add(con);
                Logcon(con);
            }

            return(controllers.Count);
        }
        public void KeyBoardStart()
        {
            var dirInput   = new SharpDX.DirectInput.DirectInput();
            var allDevices = dirInput.GetDevices();

            foreach (var item in allDevices)
            {
                if (SharpDX.DirectInput.DeviceType.Keyboard == item.Type)
                {
                    curKeyBoard = new SharpDX.DirectInput.Keyboard(dirInput);
                    curKeyBoard.Acquire();
                }
            }
            while (true)
            {
                Thread.Sleep(100);
                var curKeyboardState = curKeyBoard.GetCurrentState();
                Key curPressedKey    = new Key();;
                if (curKeyboardState.PressedKeys.Count() > 0)
                {
                    curPressedKey = curKeyboardState.PressedKeys[0];
                }
                if (curPressedKey == SharpDX.DirectInput.Key.O || curPressedKey == SharpDX.DirectInput.Key.P)
                {
                    var dir = curPressedKey == SharpDX.DirectInput.Key.O ? Direction.ClampOn : Direction.ClampOff;
                    //clampCalculator.OnClampPressed(dir);
                    Debug.WriteLine(dir.ToString());
                    continue;
                }

                if (InputDeviceInfo.isJoysMoving)
                {
                    continue;
                }
                InputDeviceInfo.isKeyBoardMoving = curKeyboardState.PressedKeys.Count() > 0 && IsControlKey(curPressedKey);
                if (InputDeviceInfo.isKeyBoardMoving)
                {
                    //InputDeviceInfo.isKeyBoardMoving = true;
                    switch (curKeyboardState.PressedKeys[0])
                    {
                    case SharpDX.DirectInput.Key.W:
                        positionCalculator.OnDirectionPressed(Direction.Up);
                        break;

                    case SharpDX.DirectInput.Key.A:
                        positionCalculator.OnDirectionPressed(Direction.Left);
                        break;

                    case SharpDX.DirectInput.Key.S:
                        positionCalculator.OnDirectionPressed(Direction.Down);
                        break;

                    case SharpDX.DirectInput.Key.D:
                        positionCalculator.OnDirectionPressed(Direction.Right);
                        break;

                    case SharpDX.DirectInput.Key.I:
                        positionCalculator.OnDirectionPressed(Direction.ZUp);
                        break;

                    case SharpDX.DirectInput.Key.K:
                        positionCalculator.OnDirectionPressed(Direction.ZDown);
                        break;

                    case SharpDX.DirectInput.Key.J:
                        positionCalculator.OnDirectionPressed(Direction.RotateLeft);
                        break;

                    case SharpDX.DirectInput.Key.L:
                        positionCalculator.OnDirectionPressed(Direction.RotateRight);
                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    positionCalculator.Stop();
                }
            }
        }
Example #41
0
        public static void _Joystic()
        {

            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;


            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                    DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
                _is_joysticConnect = true;

            }
            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                        DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
                _is_joysticConnect = true;
            }
            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                _is_joysticConnect = false;
            }

            if (_is_joysticConnect)
            {
                var joystick = new Joystick(directInput, joystickGuid);

                Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);

                // Query all suported ForceFeedback effects
                var allEffects = joystick.GetEffects();
                foreach (var effectInfo in allEffects)
                    Console.WriteLine("Effect available {0}", effectInfo.Name);

                // Set BufferSize in order to use buffered data.
                joystick.Properties.BufferSize = 128;

                // Acquire the joystick
                joystick.Acquire();

                // Poll events from joystick
                var joystickState = new JoystickState();
                bool work;
                while (_continue )
                {
                    work = false;
                    joystick.Poll();
                    var data = joystick.GetBufferedData();
                    foreach (var state in data)
                    {

                        if (state.Offset == JoystickOffset.X)
                        {
                            yaw_curr = ((32767 - state.Value) / 4096);
                            if (Math.Abs(yaw_curr - yaw_prev) >3 )
                            {
                                string mes = Convert.ToString(yaw_curr);
                                while (mes.Length < 5)
                                {
                                    mes = ' ' + mes;
                                }
                                _serialPort.WriteLine('y' + mes);
                                yaw_prev = yaw_curr;

                            }
                            work = true;
                        }
                        if (state.Offset == JoystickOffset.Z)
                        {
                            pitch_curr = ((32767 - state.Value) / 20) + pitch0;
                            if(Math.Abs(pitch_curr - pitch_prev)>100)
                            {
                                string mes = Convert.ToString(pitch_curr);
                                while (mes.Length < 5)
                                {
                                    mes = ' ' + mes;
                                }
                                _serialPort.WriteLine('p'+mes);
                                pitch_prev = pitch_curr;
                                
                            }
                            work = true;
                        }
                        if (state.Offset == JoystickOffset.RotationZ)
                        {
                            roll_curr = ((state.Value - 32767) / 20) + roll0;
                            if (Math.Abs(roll_curr - roll_prev) > 100)
                            {
                                string mes = Convert.ToString(roll_curr);
                                while (mes.Length < 5)
                                {
                                    mes = ' ' + mes;
                                }
                                _serialPort.WriteLine('r' + mes);
                                roll_prev = roll_curr;
                                
                            }
                            work = true;
                        }
                        if (state.Offset == JoystickOffset.PointOfViewControllers0) // power
                        {
                            work = true;
                            var val = state.Value;
                            switch (val)
                            {
                                case 0:
                                    if(force < 970)
                                    {
                                        force += 20;
                                        string mes = Convert.ToString(force);
                                        while (mes.Length < 5)
                                        {
                                            mes =  ' ' + mes;
                                        }
                                        _serialPort.WriteLine('f'+mes);
                                    }
                                    break;
                                case 9000:
                                    force = 0;
                                    _serialPort.WriteLine("f00000\n");
                                    break;
                                case 18000:
                                    if (force >19)
                                    {
                                        force -= 20;
                                        string mes = Convert.ToString(force);
                                        while (mes.Length < 5)
                                        {
                                            mes = ' ' + mes;
                                        }
                                        _serialPort.WriteLine('f'+mes);
                                    }
                                    break;
                                case 27000:
                                    //NOP
                                    break;
                            }
                            
                        }
                        if(work == false)
                        {
                            Thread.Sleep(200);
                        }
                    }
                }
            }
        }
Example #42
0
        public List<string> EnumerateJoystickNames()
        {
            var results = new List<string>();

            DirectInput dinput = new DirectInput();
            var devices = dinput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly);
            for (int i = 0; i < devices.Count; i++)
            {
                var device = devices[i];
                results.Add(device.InstanceName);
            }
            return results;
        }
        public static Joystick FindGamepad()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                        DeviceEnumerationFlags.AllDevices))
                joystickGuid = deviceInstance.InstanceGuid;

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                        DeviceEnumerationFlags.AllDevices))
                    joystickGuid = deviceInstance.InstanceGuid;

            // If Joystick not found, throws an error
            GamePadConnected = true;
            if (joystickGuid == Guid.Empty)
            {
                MainWindow.GPID = "No Gamepad found.";
                GamePadConnected = false;
                //Environment.Exit(1);
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);

            MainWindow.GPID = "Gamepad GUID: " + joystickGuid;

            // Query all suported ForceFeedback effects
            var allEffects = joystick.GetEffects();
            foreach (var effectInfo in allEffects)
                Console.WriteLine("Effect available {0}", effectInfo.Name);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            // Poll events from joystick
            //  while (true)
            // {
            //    joystick.Poll();
            //    var datas = joystick.GetBufferedData();
            //  foreach (var state in datas)
            //    Console.WriteLine(state);
            //}

            return joystick;
        }
Example #44
0
        //call this on call back when something is beeing plugged in or unplugged
        void InitializeJoystickIfPossible()
        {
            // try to dispose of the old joystick
            if (m_joystick != null)
            {
                m_joystick.Dispose();
                m_joystick = null;
                m_joystickConnected = false;
                m_joystickType = null;
            }
            if (m_joystick == null)
            {
                // Joystick disabled?
                if (m_joystickInstanceName == null) return;

                //  Make sure that DirectInput has been initialized
                DirectInput dinput = new DirectInput();

                //  Try to grab the joystick with the correct instance name
                foreach (var device in dinput.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly))
                {
                    if (device.InstanceName != m_joystickInstanceName)
                        continue;
                    
                    try
                    {
                        //device.Type
                        m_joystick = new Joystick(dinput, device.InstanceGuid);
                        m_joystickType = device.Type;

                        MethodInfo setCooperativeLevel = typeof(Device).GetMethod("SetCooperativeLevel",
                                                                                     new[]
                                                                                         {
                                                                                             typeof (IntPtr),
                                                                                             typeof (CooperativeLevel)
                                                                                         });

                        // Workaround for not need to reference System.Windows.Forms
                        setCooperativeLevel.Invoke(m_joystick,
                                                   new object[]
                                                       {
                                                           MyMinerGame.Static.Window.NativeWindow.Handle,
                                                           CooperativeLevel.Exclusive | CooperativeLevel.Foreground
                                                       });

                        break;
                    }
                    catch (SharpDX.SharpDXException)
                    {
                    }
                }
                
                // load and acquire joystick
                // both joystick and xbox 360 gamepad are treated as joystick device by slimdx
                if (m_joystick != null)
                {
                    int sliderCount = 0;
                    m_joystickXAxisSupported = m_joystickYAxisSupported = m_joystickZAxisSupported = false;
                    m_joystickRotationXAxisSupported = m_joystickRotationYAxisSupported = m_joystickRotationZAxisSupported = false;
                    m_joystickSlider1AxisSupported = m_joystickSlider2AxisSupported = false;
                    foreach (DeviceObjectInstance doi in m_joystick.GetObjects())
                    {
                        if ((doi.ObjectId.Flags & DeviceObjectTypeFlags.Axis) != 0)
                        {
                            // set range 0..65535 for each axis
                            m_joystick.GetObjectPropertiesById(doi.ObjectId).Range = new InputRange(0, 65535);

                            // find out which axes are supported
                            if (doi.ObjectType == ObjectGuid.XAxis) m_joystickXAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.YAxis) m_joystickYAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.ZAxis) m_joystickZAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.RxAxis) m_joystickRotationXAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.RyAxis) m_joystickRotationYAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.RzAxis) m_joystickRotationZAxisSupported = true;
                            else if (doi.ObjectType == ObjectGuid.Slider)
                            {
                                sliderCount++;
                                if (sliderCount >= 1) m_joystickSlider1AxisSupported = true;
                                if (sliderCount >= 2) m_joystickSlider2AxisSupported = true;
                            }
                        }
                    }

                    // acquire the device
                    m_joystick.Acquire();
                    m_joystickConnected = true;
                }
                dinput.Dispose();
            }
        }
Example #45
-1
        private void createJoystick()
        {
            DirectInput directInput = new DirectInput();
            Guid guid = Guid.Empty;

            //Create joystick device.
            //This process is called Direct Input Device Enumeration
            //IList<DeviceInstance>
                gameControls = directInput.GetDevices(
                DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly);

            switch(this.type)
            {
                case JoystickType.MainController:
                    if (gameControls.Count >= 1)
                        guid = gameControls[0].InstanceGuid;
                    break;
                case JoystickType.ManipulatorLeft:
                    if (gameControls.Count >= 2)
                        guid = gameControls[1].InstanceGuid;
                    break;
                case JoystickType.ManipulatorRight:
                    if (gameControls.Count >= 3)
                        guid = gameControls[2].InstanceGuid;
                    break;
            }

            if(guid != Guid.Empty)
                joystick = new SharpDX.DirectInput.Joystick(directInput, guid);

            if (joystick == null)
            {
                //Throw exception if joystick not found.
                throw new Exception("No joystick found.");
            }
        }
        public void CaptureJoysticks()
        {
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find all joysticks connected to the system
            IList<DeviceInstance> connectedJoysticks = new List<DeviceInstance>();
            // - look for gamepads
            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
            {
                connectedJoysticks.Add(deviceInstance);
            }
            // - look for joysticks
            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
            {
                connectedJoysticks.Add(deviceInstance);
            }

            // Use the two first joysticks found
            if (connectedJoysticks.Count >= 1)
            {
                joystick1 = new Joystick(directInput, connectedJoysticks[0].InstanceGuid);
                Joystick1DeviceName = connectedJoysticks[0].InstanceName;
                joystick1.Acquire();
            }
            if (connectedJoysticks.Count >= 2)
            {
                joystick2 = new Joystick(directInput, connectedJoysticks[1].InstanceGuid);
                Joystick2DeviceName = connectedJoysticks[1].InstanceName;
                joystick2.Acquire();
            }
        }