Beispiel #1
1
        protected void CreateInputDevices(Control target)
        {
            // create keyboard device.
            keyboard = new Device(SystemGuid.Keyboard);
            if (keyboard == null)
            {
                throw new Exception("No keyboard found.");
            }

            // create mouse device.
            mouse = new Device(SystemGuid.Mouse);
            if (mouse == null)
            {
                throw new Exception("No mouse found.");
            }

            // set cooperative level.
            keyboard.SetCooperativeLevel(target, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);

            mouse.SetCooperativeLevel(target, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);

            // Acquire devices for capturing.
            keyboard.Acquire();
            mouse.Acquire();
        }
Beispiel #2
0
 private void KeyboardForm_Activated(object sender, System.EventArgs e)
 {
     if (null != applicationDevice)
     {
         try{ applicationDevice.Acquire(); }
         catch (DirectXException) {}
     }
 }
Beispiel #3
0
		/// <summary>
		/// Plugin entry point 
		/// </summary>
		public override void Load() 
		{
			drawArgs = ParentApplication.WorldWindow.DrawArgs;
			DeviceList dl = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
			dl.MoveNext();
			if(dl.Current==null)
			{
				throw new ApplicationException("No joystick detected.  Please check your connections and verify your device appears in Control panel -> Game Controllers.");
			}
			DeviceInstance di = (DeviceInstance) dl.Current;
			joystick = new Device( di.InstanceGuid );
			joystick.SetDataFormat(DeviceDataFormat.Joystick);
			joystick.SetCooperativeLevel(ParentApplication,  
				CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
			foreach(DeviceObjectInstance d in joystick.Objects) 
			{
				// For axes that are returned, set the DIPROP_RANGE property for the
				// enumerated axis in order to scale min/max values.
				if((d.ObjectId & (int)DeviceObjectTypeFlags.Axis)!=0) 
				{
					// Set the AxisRange for the axis.
					joystick.Properties.SetRange(ParameterHow.ById, d.ObjectId, new InputRange(-AxisRange, AxisRange));
					joystick.Properties.SetDeadZone(ParameterHow.ById, d.ObjectId, 1000); // 10%
				}
			}

			joystick.Acquire();

			// Start a new thread to poll the joystick
			// TODO: The Device supports events, use them
			joyThread = new Thread( new ThreadStart(JoystickLoop) );
			joyThread.IsBackground = true;
			joyThread.Start();
		}
 public void MouseInit(Control parent)
 {
     m_mouse = new Device(SystemGuid.Mouse);
     m_mouse.SetCooperativeLevel(parent, CooperativeLevelFlags.Background |
                                 CooperativeLevelFlags.NonExclusive);
     m_mouse.Acquire();
 }
Beispiel #5
0
        private void AddJoystickDevices(IntPtr windowHandle)
        {
            DeviceList gameControllerList = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);

            for (int i = 0; i < gameControllerList.Count; i++)
            {
                gameControllerList.MoveNext();
                DeviceInstance deviceInstance = (DeviceInstance)gameControllerList.Current;

                Device device = new Device(deviceInstance.InstanceGuid);

                if (device.DeviceInformation.ProductGuid != new Guid("0306057e-0000-0000-0000-504944564944") &&       // Wiimotes are excluded
                    !CheckIfDirectInputDeviceExists(device))
                {
                    device.SetCooperativeLevel(windowHandle, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                    device.SetDataFormat(DeviceDataFormat.Joystick);
                    device.Acquire();

                    JoystickInput input = new JoystickInput(device);
                    AddInputDevice(input);
                    input.InitCurrentlyInvokedInput();

                    InvokeNewInputDeviceEvent(input.DeviceInstanceId, input);
                }
            }
        }
Beispiel #6
0
 private void InitJoystick()
 {
     //W pętli foreach znajdowane są wszystkie podłączone urządzenia, które są należą do klasy urządzeń GameControl
     foreach (
         DeviceInstance di in
         Manager.GetDevices(
             DeviceClass.GameControl,
             EnumDevicesFlags.AttachedOnly))
     {
         //Tworzona jest nowa instancja urządzenia
         joystick = new Device(di.InstanceGuid);
         //Ustawiamy TextBox, oraz podświetlenie informujące o tym, że joystick został znaleziony i podłączony
         connectionStatusTextBox.Text      = "Joystick Polaczony";
         connectionStatusTextBox.BackColor = Color.Green;
         //Pobieramy i ustawiamy nazwę joysticka
         joystickNameTextBox.Text = di.InstanceName;
         //Ustawiamy parametry połączenia (między innymi aby joystick działał, gdy okno będzie nieaktywne)
         joystick.SetCooperativeLevel(this, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
         //Ustawiamy typ urządzenia jako joystick
         joystick.SetDataFormat(DeviceDataFormat.Joystick);
         //Potwierdzamy i zapisujemy dane o urządzeniu
         joystick.Acquire();
         break;
     }
     //Jeżeli nie znaleziono joysticka
     if (joystick == null)
     {
         //Ustawiamy odpowiedni komunikat
         connectionStatusTextBox.Text      = "Joystick Nie Polaczony";
         connectionStatusTextBox.BackColor = Color.Red;
         joystickNameTextBox.Text          = "";
         return;
     }
 }
Beispiel #7
0
        private void frmUI_Load(object sender, System.EventArgs e)
        {
            threadData = new Thread(new ThreadStart(this.MouseEvent));
            threadData.Start();

            eventFire = new AutoResetEvent(false);

            // Create the device.
            try
            {
                applicationDevice = new Device(SystemGuid.Mouse);
            }
            catch (InputException)
            {
                MessageBox.Show("Unable to create device. Sample will now exit.");
                Close();
            }
            // Set the cooperative level for the device.
            applicationDevice.SetCooperativeLevel(this, CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Foreground);
            // Set a notification event.
            applicationDevice.SetEventNotification(eventFire);
            // Acquire the device.
            try{ applicationDevice.Acquire(); }
            catch {}
        }
Beispiel #8
0
        public KeyboardState GetKBState()
        {
            KeyboardState state = null;

            try {
                state = localDevice.GetCurrentKeyboardState();
            }
            catch (InputException) {
                do
                {
                    Application.DoEvents();
                    try{ localDevice.Acquire(); }
                    catch (InputLostException) {
                        Thread.Sleep(2);
                        continue;
                    }
                    catch (OtherApplicationHasPriorityException) {
                        Thread.Sleep(2);
                        continue;
                    }

                    break;
                }while(true);
            }
            return(state);
        }
Beispiel #9
0
 private bool TryAcquire()
 {
     if (_device == null ||
         _hWnd != NativeMethods.GetForegroundWindow())
     {
         return(false);
     }
     try
     {
         _device.Acquire();
         _isAcquired = true;
         return(true);
     }
     catch (OtherApplicationHasPriorityException)
     {
     }
     catch (InputLostException)
     {
     }
     catch (Exception ex)
     {
         Logger.Error(ex);
     }
     return(false);
 }
Beispiel #10
0
        private void AddKeyboardDevices(IntPtr windowHandle)
        {
            DeviceList keyboardControllerList = Manager.GetDevices(DeviceClass.Keyboard, EnumDevicesFlags.AttachedOnly);

            for (int i = 0; i < keyboardControllerList.Count; i++)
            {
                keyboardControllerList.MoveNext();
                DeviceInstance deviceInstance = (DeviceInstance)keyboardControllerList.Current;

                Device device = new Device(deviceInstance.InstanceGuid);

                if (!CheckIfDirectInputDeviceExists(device))
                {
                    device.SetCooperativeLevel(windowHandle, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                    device.SetDataFormat(DeviceDataFormat.Keyboard);
                    device.Acquire();

                    KeyboardInput input = new KeyboardInput(device);
                    AddInputDevice(input);
                    input.InitCurrentlyInvokedInput();

                    InvokeNewInputDeviceEvent(input.DeviceInstanceId, input);
                }
            }
        }
        public XBoxController()
        {
            DeviceList     devices;
            DeviceInstance dev;

            try
            {
                devices = Manager.GetDevices(DeviceType.Gamepad, EnumDevicesFlags.AllDevices);
                devices.MoveNext();
                dev = (Microsoft.DirectX.DirectInput.DeviceInstance)devices.Current;



                try
                {
                    xboxController = new Device(dev.ProductGuid);
                }
                catch (Exception ex)
                {
                    xboxController = new Device(dev.InstanceGuid);
                }

                //gamepadDevice.SetCooperativeLevel(, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);

                Thread t = new Thread(new ThreadStart(DoWork));
                t.Start();
                WAIT_FOR[0] = JOYSTICK_EVENT;
                xboxController.SetEventNotification(JOYSTICK_EVENT);
                xboxController.Acquire();
            }
            catch (Exception e) { }
        }
Beispiel #12
0
        public void Init_Joystick_Device()
        {
            //create joystick device.
            foreach (DeviceInstance di in Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly))
            {
                Joystick        = new Device(di.InstanceGuid);
                break;
            }

            if (Joystick != null)
            {
                joystickStatus  = true;
            }

            //Set joystick axis ranges.
            foreach (DeviceObjectInstance doi in Joystick.Objects)
            {
                if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                {
                    Joystick.Properties.SetRange(ParameterHow.ById, doi.ObjectId, new InputRange(1, 126));
                }
            }

            //Set joystick axis mode absolute.
            Joystick.Properties.AxisModeAbsolute = true;
            //Joystick.SetCooperativeLevel(this, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);

            //Acquire devices for capturing.
            Joystick.Acquire();
        }
Beispiel #13
0
        public void ChargerVolant()
        {
            //Find all the GameControl devices that are attached.

            DeviceList gameControllerList = Manager.GetDevices(DeviceType.Joystick, EnumDevicesFlags.AttachedOnly);

            // check that we have at least one device.
            if (gameControllerList.Count > 0)
            {
                try
                {
                    // Move to the first device
                    gameControllerList.MoveNext();
                    DeviceInstance deviceInstance = (DeviceInstance)gameControllerList.Current;

                    // create a device from this controller.
                    ElVolant = new Device(deviceInstance.InstanceGuid);
                    //Volant.SetCooperativeLevel(CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);

                    // Tell DirectX that this is a Joystick.
                    ElVolant.SetDataFormat(DeviceDataFormat.Joystick);
                    // Finally, acquire the device.
                    ElVolant.Acquire();
                    //ElButtons.Acquire();
                }
                catch (Exception e) { }
            }

            else
            {
                this.Enabled = !this.Enabled;
            }
        }
Beispiel #14
0
		private void SetupJoystick()
		{
			DeviceList list = Manager.GetDevices(Microsoft.DirectX.DirectInput.DeviceType.Joystick, EnumDevicesFlags.AttachedOnly);
			System.Diagnostics.Debug.WriteLine(String.Format("Joystick list count: {0}", list.Count));
			if (list.Count > 0)
			{
				while (list.MoveNext())
				{
					// Move to the first device
					DeviceInstance deviceInstance = (DeviceInstance)list.Current;
					try
					{						
						// create a device from this controller.
						Device = new Device(deviceInstance.InstanceGuid);
						System.Diagnostics.Debug.WriteLine(String.Format("Device: {0} / {1}", Device.DeviceInformation.InstanceName, Device.DeviceInformation.ProductName));
						Device.SetCooperativeLevel(Game.Window.Handle, CooperativeLevelFlags.Background | CooperativeLevelFlags.Exclusive);
						// Tell DirectX that this is a Joystick.
						Device.SetDataFormat(DeviceDataFormat.Joystick);
						// Finally, acquire the device.	
						Device.Acquire();
						System.Diagnostics.Debug.WriteLine(String.Format("Device acquired"));
						break;
					}
					catch
					{						
						Device = null;
						System.Diagnostics.Debug.WriteLine(String.Format("Device acquire or data format setup failed"));
					}
				}
			}
		}
Beispiel #15
0
 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
     RefreshConnectionData();
     foreach (DeviceInstance instance in Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly))
     {
         device = new Device(instance.ProductGuid);
         device.SetCooperativeLevel(null, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
         foreach (DeviceObjectInstance doi in device.Objects)
         {
             if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
             {
                 device.Properties.SetRange(
                     ParameterHow.ById,
                     doi.ObjectId,
                     new InputRange(0, 100));
             }
         }
         device.Acquire();
     }
     try
     {
         label1.FontSize   = 18;
         label1.Foreground = Brushes.Green;
         label1.FontWeight = FontWeights.Bold;
         label1.Content    = device.DeviceInformation.InstanceName;
     }
     catch (NullReferenceException)
     {
         label1.FontSize   = 14;
         label1.Foreground = Brushes.Red;
         label1.FontWeight = FontWeights.UltraBold;
         label1.Content    = "Joystick not found! Please check the connection and restart this programm";
     }
 }
Beispiel #16
0
        private static byte[] g_LastDetect;         // used by timer when in detect mode: want to check ALL switches

        private static void Attach()
        {
            // creates DirectX device, but does not start timer
            if (m_Joystick != null)
            {
                return;
            }

            try
            {
                // if VS gives waffle here about LoaderLock when debugging, turn off Debug menu > Exceptions > Managed Debug Assistants > LoaderLock
                foreach (DeviceInstance di in Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly))
                {
                    m_Joystick = new Device(di.InstanceGuid);
                    break;
                }

                if (m_Joystick == null)
                {
                    OnError("Failed to connect to DirectX joystick device - no joystick attached?");
                    return;
                }

                m_Joystick.SetCooperativeLevel(m_EventForm.Handle, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                m_Joystick.Acquire();
            }
            catch (Exception ex)
            {
                OnError("Error connecting to DirectX joystick device: " + ex.Message);
                return;
            }
        }
 public void KeyboardInit(Control parent)
 {
     m_keyboard = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
     m_keyboard.SetCooperativeLevel(parent, CooperativeLevelFlags.Background |
                                    CooperativeLevelFlags.NonExclusive);
     m_keyboard.Acquire();
 }
Beispiel #18
0
        //* ────────────-_______________________*
        //* constructor & destructor ───────────────────────*

        //* -----------------------------------------------------------------------*
        /// <summary>コンストラクタ。</summary>
        ///
        /// <param name="guid">デバイスのインスタンスGUID</param>
        /// <param name="hWnd">ウィンドウ ハンドル</param>
        public CLegacyInput(Guid guid, IntPtr hWnd)
            : base(CStateLegacyInput.instance, new CPrivateMembers())
        {
            _privateMembers = (CPrivateMembers)privateMembers;
            string errorReport = string.Empty;

            try
            {
                device = new Device(guid);
                device.SetDataFormat(DeviceDataFormat.Joystick);
                capsReport =
                    device.DeviceInformation.createCapsReport() + device.Caps.createCapsReport();
                availableForceFeedback = initializeForceFeedBack(ref errorReport);
                initializeAxis();
                device.Acquire();
                startForceFeedback = _startForceFeedback;
            }
            catch (Exception e)
            {
                string err = device == null ?
                             Resources.INPUT_ERR_LEGACY_INIT_FAILED :
                             Resources.INPUT_ERR_LEGACY_INIT_FAILED_MAYBE;
                errorReport += err + Environment.NewLine + e.ToString();
            }
            this.errorReport = errorReport;
        }
Beispiel #19
0
        private void UpdateDevices()
        {
            _devices.Clear();
            _buttons.Clear();

            foreach (DeviceInstance instance in Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly))
            {
                // var productName = instance.ProductName;

                var device = new Device(instance.ProductGuid);

                // device.SetCooperativeLevel(null, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);

                device.Acquire();

                _devices.Add(device);
                _buttons.Add(device.DeviceInformation.ProductGuid, null);
            }

            var timer = new DispatcherTimer();

            timer.Tick    += new EventHandler(timer_Tick);
            timer.Interval = new TimeSpan(0, 0, 0, 0, 10);
            timer.Start();
        }
Beispiel #20
0
 private void AcquireImage(bool showUI)
 {
     try
     {
         this._sessionCount = 0;
         this._imageCount   = 0;
         if (this._deviceManager.ShowDefaultDeviceSelectionDialog())
         {
             Device defaultDevice = this._deviceManager.DefaultDevice;
             defaultDevice.ShowUI = showUI;
             defaultDevice.DisableAfterAcquire  = !showUI;
             defaultDevice.ImageAcquired       += new EventHandler <ImageAcquiredEventArgs>(this.device_ImageAcquired);
             defaultDevice.ScanCompleted       += new EventHandler(this.device_ScanCompleted);
             defaultDevice.UserInterfaceClosed += new EventHandler(this.device_UserInterfaceClosed);
             defaultDevice.ScanCanceled        += new EventHandler(this.device_ScanCanceled);
             defaultDevice.ScanFailed          += new EventHandler <ScanFailedEventArgs>(this.device_ScanFailed);
             defaultDevice.Acquire();
         }
         else
         {
             MessageBox.Show("Devices is not selected.");
         }
     }
     catch (TwainException twainException)
     {
         MessageBox.Show(twainException.Message);
         this.ScanComplete();
     }
 }
Beispiel #21
0
 /// <summary>
 /// Background thread runs this function in a loop reading joystick state.
 /// </summary>
 void JoystickLoop()
 {
     while (true)
     {
         Thread.Sleep(20);
         try
         {
             // Poll the device for info.
             joystick.Poll();
             HandleJoystick();
         }
         catch (InputException inputex)
         {
             if ((inputex is NotAcquiredException) || (inputex is InputLostException))
             {
                 // Check to see if either the app
                 // needs to acquire the device, or
                 // if the app lost the device to another
                 // process.
                 try
                 {
                     // Acquire the device.
                     joystick.Acquire();
                 }
                 catch (InputException)
                 {
                     // Failed to acquire the device.
                     // This could be because the app
                     // doesn't have focus.
                     Thread.Sleep(1000);
                 }
             }
         }
     }
 }
		public Paddle()
		{

			foreach(DeviceInstance di in Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly))
			{
				paddleDevice = new Device(di.InstanceGuid);
				break;
			}

			if(paddleDevice != null)
			{
				try
				{
					paddleDevice.SetDataFormat(DeviceDataFormat.Joystick);
					paddleDevice.Acquire();
				}
				catch(InputException)
				{
					
				}
			}

			pollTimer = new System.Timers.Timer(1);
			pollTimer.Enabled = false;
			pollTimer.Elapsed += new System.Timers.ElapsedEventHandler(pollTimer_Elapsed);
			
		}
Beispiel #23
0
 /// <summary>
 /// Acquires the joystick if necessary, and starts polling the joystick for information.
 /// Uses the same concepts behind the DirectX 9 SDK Joystick sample download.
 /// </summary>
 public void GetData()
 {
     if (null == _applicationDevice)
     {
         return;
     }
     try
     {
         _applicationDevice.Poll();
     }
     catch (InputException inputex)
     {
         if (inputex is NotAcquiredException | inputex is InputLostException)
         {
             try
             {
                 _applicationDevice.Acquire();
             }
             catch
             {
                 return;
             }
         }
     }
     try
     {
         _state = _applicationDevice.CurrentJoystickState;
     }
     catch
     {
         return;
     }
 }
Beispiel #24
0
        //Function of initialize device
        public static void InitDevices()
        {
            //create joystick device.
            foreach (DeviceInstance di in Manager.GetDevices(
                DeviceClass.GameControl,
                EnumDevicesFlags.AttachedOnly))
            {
                joystick = new Device(di.InstanceGuid);
                break;
            }
            if (joystick == null)
            {
                //Throw exception if joystick not found.
            }
            //Set joystick axis ranges.
            else {
                foreach (DeviceObjectInstance doi in joystick.Objects)
                {
                    if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                    {
                        joystick.Properties.SetRange(
                            ParameterHow.ById,
                            doi.ObjectId,
                            new InputRange(-5000, 5000));
                    }

                }
                joystick.Properties.AxisModeAbsolute = true;

                joystick.SetCooperativeLevel(null,CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
                //Acquire devices for capturing.
                joystick.Acquire();
                state = joystick.CurrentJoystickState;
            }
        }
Beispiel #25
0
        public static void Init(System.Windows.Forms.Control targetControl)
        {
            if (_Keyboard == null)
            {
                _Keyboard = new Keyboard();
            }
            if (_EmptyState == null)
            {
                _EmptyState = new Keyboard();
            }
            _Device = new Device(SystemGuid.Keyboard);
            _Device.SetCooperativeLevel(targetControl, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.NonExclusive);
            _Device.SetDataFormat(DeviceDataFormat.Keyboard);

            Timer = new Timer();
            double InitTime = Timer.GetAbsoluteTime();

            for (int i = 0; i < _Keyboard.KeysElapsedTime.Length; i++)
            {
                _Keyboard.KeysElapsedTime[i] = InitTime;
            }

            try { _Device.Acquire(); }
            catch (DirectXException e) { Console.WriteLine(e.Message); }
        }
Beispiel #26
0
        public void Poll()
        {
            LockMouse = false;
            try
            {
                CurrentMouseState = Device.CurrentMouseState;
                ButtonState       = CurrentMouseState.GetMouseButtons();

                for (int i = 0; i < ButtonState.Length; i++)
                {
                    if (ButtonsHeld[i])
                    {
                        ButtonsPressed[i] = false;
                    }
                    else
                    {
                        ButtonsPressed[i] = (ButtonState[i] & 128) > 0;
                    }

                    ButtonsHeld[i] = (ButtonState[i] & 128) > 0;
                }
            }
            catch (NotAcquiredException)
            {
                try { _Device.Acquire(); }
                catch (Exception) { }
            }
            catch (InputException) { }
            catch (NullReferenceException) { }
        }
Beispiel #27
0
        public static void InitDevices()             //Function of initialize device
        {
            //create joystick device.
            foreach (DeviceInstance di in Manager.GetDevices(
                         DeviceClass.GameControl,
                         EnumDevicesFlags.AttachedOnly))
            {
                joystick = new Device(di.InstanceGuid);
                break;
            }
            if (joystick == null)
            {
                //Throw exception if joystick not found.
            }
            //Set joystick axis ranges.
            else
            {
                foreach (DeviceObjectInstance doi in joystick.Objects)
                {
                    if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                    {
                        joystick.Properties.SetRange(
                            ParameterHow.ById,
                            doi.ObjectId,
                            new InputRange(-5000, 5000));
                    }
                }
                joystick.Properties.AxisModeAbsolute = true;

                joystick.SetCooperativeLevel(null, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
                //Acquire devices for capturing.
                joystick.Acquire();
                state = joystick.CurrentJoystickState;
            }
        }
Beispiel #28
0
        /// <summary>
        /// Acquire the named joystick. You can find this joystick through the <see cref="FindJoysticks"/> method.
        /// </summary>
        /// <param name="name">Name of the joystick.</param>
        /// <returns>The success of the connection.</returns>
        public bool AcquireJoystick(string name)
        {
            try
            {
                DeviceList gameControllerList = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
                int        i     = 0;
                bool       found = false;
                // loop through the devices.
                foreach (DeviceInstance deviceInstance in gameControllerList)
                {
                    if (deviceInstance.InstanceName == name)
                    {
                        found = true;
                        // create a device from this controller so we can retrieve info.
                        joystickDevice = new Device(deviceInstance.InstanceGuid);
                        joystickDevice.SetCooperativeLevel(hWnd,
                                                           CooperativeLevelFlags.Background |
                                                           CooperativeLevelFlags.NonExclusive);
                        break;
                    }

                    i++;
                }

                if (!found)
                {
                    return(false);
                }

                // Tell DirectX that this is a Joystick.
                joystickDevice.SetDataFormat(DeviceDataFormat.Joystick);

                // Finally, acquire the device.
                joystickDevice.Acquire();

                // How many axes?
                // Find the capabilities of the joystick
                DeviceCaps cps    = joystickDevice.Caps;
                string     strMsg = "Joystick Axis: " + cps.NumberAxes;
                MessageBox.Show(strMsg);
                strMsg = "Joystick Buttons: " + cps.NumberButtons;
                MessageBox.Show(strMsg);
                //Ojw.CMessage.Write("Joystick Axis: " + cps.NumberAxes);
                //Ojw.CMessage.Write("Joystick Buttons: " + cps.NumberButtons);

                axisCount = cps.NumberAxes;

                UpdateStatus();
            }
            catch (Exception err)
            {
                //Ojw.CMessage.Write_Error("FindJoysticks()");
                //Ojw.CMessage.Write_Error(err.Message);
                //Ojw.CMessage.Write_Error(err.StackTrace);
                return(false);
            }

            return(true);
        }
Beispiel #29
0
 public MouseInput(Control parent)
 {
     // Create our mouse device
     device = new Device(SystemGuid.Mouse);
     device.SetCooperativeLevel(parent, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
     device.Properties.AxisModeAbsolute = false;
     device.Acquire();
 }
Beispiel #30
0
 private void MainForm_Activated(object sender, System.EventArgs e)
 {
     if (null != applicationDevice)
     {
         try{ applicationDevice.Acquire(); }
         catch (InputException) {}
     }
 }
 public MouseInput(Control parent)
 {
     // Create our mouse device
     device = new Device(SystemGuid.Mouse);
     device.SetCooperativeLevel(parent, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
     device.Properties.AxisModeAbsolute = false;
     device.Acquire();
 }
Beispiel #32
0
        // ===========================================================================================
        // JoyStick Initialize========================================================================
        private void InitJoyStick()
        {
            //create joystick device.--------------------------------
            try
            {
                // search for devices
                foreach (DeviceInstance device in Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly))
                {
                    // create the device
                    try
                    {
                        joystick = new Device(device.InstanceGuid);
                    }
                    catch (DirectXException)
                    {
                    }
                }

                if (joystick == null)
                {
                    //Throw exception if joystick not found.
                    throw new Exception("No joystick found.");
                }
                else
                {
                    //listBox2.Items.Add("Success to open Joystick.");
                }

                foreach (DeviceObjectInstance deviceObject in joystick.Objects)
                {
                    if ((deviceObject.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                    {
                        joystick.Properties.SetRange(ParameterHow.ById,
                                                     deviceObject.ObjectId,
                                                     new InputRange(-1000, 1000));
                    }
                }
                //Set joystick axis mode absolute.
                joystick.Properties.AxisModeAbsolute = true;

                //set cooperative level.
                joystick.SetCooperativeLevel(
                    this,
                    CooperativeLevelFlags.NonExclusive |
                    CooperativeLevelFlags.Background);

                // acquire the device
                joystick.Acquire();
                joystick_exist = true;
            }
            catch
            {
                joystick_exist = false;
                //listBox2.Items.Add("Fail to open Joystick.");
            }

            //create joystick device end.--------------------------------
        }
Beispiel #33
0
 private void frmUI_Activated(object sender, System.EventArgs e)
 {
     // Acquire the device whenever the application window is activated.
     if (null != applicationDevice)
     {
         try{ applicationDevice.Acquire(); }
         catch {}
     }
 }
Beispiel #34
0
        private void Connect2Joystick()
        {
            richTextBox1.Text = "Settings:";
            try
            {
                // Find all the GameControl devices that are attached.
                DeviceList gameControllerList = Manager.GetDevices(
                    DeviceClass.GameControl,
                    EnumDevicesFlags.AttachedOnly);

                // check that we have at least one device.
                if (gameControllerList.Count > 0)
                {
                    timer1.Start(); // Read Joystick status by polling base on a timer_tick

                    // Move to the first device
                    gameControllerList.MoveNext();
                    DeviceInstance deviceInstance = (DeviceInstance)
                                                    gameControllerList.Current;

                    // create a device from this controller.
                    joystickDevice = new Device(deviceInstance.InstanceGuid);
                    joystickDevice.SetCooperativeLevel(this,
                                                       CooperativeLevelFlags.Background |
                                                       CooperativeLevelFlags.NonExclusive);


                    // Tell DirectX that this is a Joystick.
                    joystickDevice.SetDataFormat(DeviceDataFormat.Joystick);

                    // Finally, acquire the device.
                    joystickDevice.Acquire();

                    // Find the capabilities of the joystick
                    DeviceCaps cps = joystickDevice.Caps;

                    // number of Axes
                    richTextBox1.Text += ("\n Joystick Axes = " + cps.NumberAxes);

                    // number of Buttons
                    richTextBox1.Text += ("\n Joystick Buttons = " + cps.NumberButtons);

                    // number of PoV hats
                    richTextBox1.Text += ("\n Joystick PoV hats = "
                                          + cps.NumberPointOfViews);
                }
                else
                {
                    // "There is no Joystics available!"
                    MessageBox.Show("There is no Joystics available!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
Beispiel #35
0
        /// <summary>
        /// Initializes a new instance of KeyboardDevice.
        /// </summary>
        public KeyboardDevice( Form form )
        {
            keyboard = new Device( SystemGuid.Keyboard );

            keyboard.SetCooperativeLevel( form, CooperativeLevelFlags.Background |
                CooperativeLevelFlags.NonExclusive );

            keyboard.Acquire();
        }
Beispiel #36
0
        internal Mouse(System.Windows.Forms.Control owner, bool useWindowsCursor)
        {
            // This is needed to hide and show the Windows cursor
            mOwner = owner;



            mLastClickTime = new double[NumberOfButtons];
            mLastPushTime  = new double[NumberOfButtons];
            mDoubleClick   = new bool[NumberOfButtons];
            mDoublePush    = new bool[NumberOfButtons];

            mMouseButtonClicked = new bool[NumberOfButtons];
            mMouseButtonPushed  = new bool[NumberOfButtons];

            mMouseOffset = new MouseOffset[NumberOfButtons];

            mMouseOffset[(int)MouseButtons.LeftButton]   = MouseOffset.Button0;
            mMouseOffset[(int)MouseButtons.RightButton]  = MouseOffset.Button1;
            mMouseOffset[(int)MouseButtons.MiddleButton] = MouseOffset.Button2;
            mMouseOffset[(int)MouseButtons.XButton1]     = MouseOffset.Button3;
            mMouseOffset[(int)MouseButtons.XButton2]     = MouseOffset.Button4;

            mMouseDevice = new Device(SystemGuid.Mouse);
            mMouseDevice.SetDataFormat(DeviceDataFormat.Mouse);

            if (useWindowsCursor)
            {
                mWindowsCursorVisible = true;
                mMouseDevice.SetCooperativeLevel(owner, CooperativeLevelFlags.Foreground |
                                                 CooperativeLevelFlags.NonExclusive);
            }
            else
            {
                mWindowsCursorVisible = false;
                mMouseDevice.SetCooperativeLevel(owner, CooperativeLevelFlags.Foreground |
                                                 CooperativeLevelFlags.Exclusive);
            }

            try
            { mMouseDevice.Acquire(); }
            catch (InputLostException)
            {
                //				return;
            }
            catch (OtherApplicationHasPriorityException)
            {
                //				return;
            }
            catch (System.ArgumentException)
            {
            }

            // i don't know why this doesn't work, but input still works without it.
            mMouseDevice.Properties.BufferSize = 5;
        }
Beispiel #37
0
 public MafiaInput(Form form)
 {
     this.form = form;
     device = new Device(SystemGuid.Keyboard);
     device.Acquire();
     prevLeft = prevUp = prevRight = prevDown = false;
     prevEnter = prevSpace = false;
     prevAlt = false;
     prevEsc = false;
 }
Beispiel #38
0
        /// <summary>
        /// Creates a new Mouse.
        /// </summary>
        /// <param name="game">Game.</param>
        public Mouse(Game game)
            : base("Mouse")
        {
            mouse = new Device(SystemGuid.Mouse);
            mouse.SetCooperativeLevel(game, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
            mouse.Acquire();

            empty = mouse.CurrentMouseState;
            Reset();
        }
Beispiel #39
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SlimDXKeyboard"/> class.
        /// </summary>
        /// <param name="control">The control.</param>
        public SlimDXKeyboard(Control control)
        {
            var directInput = DirectInput.FromPointer(control.Handle);

            mKeyboard = new Device<KeyboardState>(directInput, SystemGuid.Keyboard);
            mKeyboard.SetCooperativeLevel(control,
                CooperativeLevel.Foreground | CooperativeLevel.Exclusive | CooperativeLevel.NoWinKey);

            mKeyboard.Acquire();
        }
Beispiel #40
0
        public Input(Control parent, CooperativeLevelFlags keyboardFlags, CooperativeLevelFlags mouseFlags)
        {
            keyboard = new Device(SystemGuid.Keyboard);
            keyboard.SetCooperativeLevel(parent, keyboardFlags);
            keyboard.Acquire();

            mouse = new Device(SystemGuid.Mouse);
            mouse.SetCooperativeLevel(parent, mouseFlags);
            mouse.Acquire();
        }
 public gamePad(Guid gamepadInstanceGuid, bool autoPoll)
 {
     device = new Device(gamepadInstanceGuid);
     device.SetDataFormat(DeviceDataFormat.Joystick);
     if (autoPoll == true)//If autopoll is on then continuous poll the pad in a seperate thread and return the results every change
     {
         new Thread(new ThreadStart(PollPad)).Start();//Start polling gamepad for buttons
         device.SetEventNotification(gamePadUpdate);
     }
     device.Acquire();
 }
Beispiel #42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SlimDXMouse"/> class.
        /// </summary>
        /// <param name="control">The control.</param>
        public SlimDXMouse(Control control)
        {
            mAxesActions = new Dictionary<Axis, AxisAction>(3);
            var directInput = DirectInput.FromPointer(control.Handle);

            mMouse = new Device<MouseState>(directInput, SystemGuid.Mouse);
            mMouse.SetCooperativeLevel(control,
                CooperativeLevel.Foreground | CooperativeLevel.Exclusive);

            mMouse.Acquire();
        }
Beispiel #43
0
        public void Init(Control parent)
        {
            _keyboard = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
            _keyboard.SetCooperativeLevel(parent, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
            _keyboard.Acquire();

            _mouse = new Device(SystemGuid.Mouse);
            _mouse.SetCooperativeLevel(parent,
                CooperativeLevelFlags.NonExclusive |
                CooperativeLevelFlags.Background);

            _mouse.Acquire();
        }
        public DInputHook(IntPtr hWnd)
        {
            this.hWnd = hWnd;
            keyboard = new Device(SystemGuid.Keyboard);
            keyboardUpdated = new AutoResetEvent(false);
            keyboard.SetCooperativeLevel(hWnd, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);
            keyboard.SetEventNotification(keyboardUpdated);

            appShutdown = new ManualResetEvent(false);

            threadloop = new Thread(new ThreadStart(ThreadFunction));
            keyboard.Acquire();
            threadloop.Start();
        }
Beispiel #45
0
		public Gamepad(Window wnd) {
			foreach (DeviceInstance instance in Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly)) {
				_joystick = new Device(instance.InstanceGuid);
				break;
			}
			if (_joystick == null) {
				Tools.ShowMessage("No gamepad found!", MessageType.Error);
			}
			else {
				var helper = new WindowInteropHelper(wnd);
				_joystick.SetCooperativeLevel(helper.Handle, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
				_joystick.Properties.BufferSize = 0x80;
				_joystick.Acquire();
				IsValid = true;
			}
		}
        public InputToolBox(GraphicEngine GE)
        {
            GE_object = GE;
            try
            {
                KeyBoardDevice = new Microsoft.DirectX.DirectInput.Device(SystemGuid.Keyboard);
                KeyBoardDevice.SetDataFormat(DeviceDataFormat.Keyboard);
                KeyBoardDevice.Acquire();

                MouseDevice = new Device(SystemGuid.Mouse);
                MouseDevice.SetDataFormat(DeviceDataFormat.Mouse);
                MouseDevice.Acquire();
            }
            catch (DirectXException ex)
            {
                MessageBox.Show(ex.Message, ex.Source);
            }
        }
Beispiel #47
0
        private void Form1_Load(object sender, EventArgs e)
        {
            //create joystick device.
            foreach (
                DeviceInstance di in
                Manager.GetDevices(
                    DeviceClass.GameControl,
                    EnumDevicesFlags.AttachedOnly))
            {
                joystick = new Device(di.InstanceGuid);
                break;
            }

            if (joystick == null)
            {
                //Throw exception if joystick not found.
                throw new Exception("No joystick found.");
            }

            //Set joystick axis ranges.
            foreach (DeviceObjectInstance doi in joystick.Objects)
            {
                if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                {
                    joystick.Properties.SetRange(
                        ParameterHow.ById,
                        doi.ObjectId,
                        new InputRange(1, 32767));
                }
            }

            //Set joystick axis mode absolute.
            joystick.Properties.AxisModeAbsolute = true;

            //set cooperative level.
            joystick.SetCooperativeLevel(
                this,
                CooperativeLevelFlags.NonExclusive |
                CooperativeLevelFlags.Background);

            //Acquire devices for capturing.
            joystick.Acquire();
        }
Beispiel #48
0
        private static void Main(string[] args)
        {
            _acquisition = new Acquisition();
            _acquisition.ImageAcquired += image_acquired;
            _acquisition.AcquireCanceled += acquire_canceled;
            _acquisition.AcquireFinished += acq_AcquireFinished;
            _acquisition.AsynchronousException += acq_AsynchronousException;

            _device = _acquisition.ShowSelectSource();

            try
            {
                if (_device.TryOpen())
                {
                    _device.AutoScan = true;
                    _device.HideInterface = true;
                    _device.ModalAcquire = false;
                    _device.DocumentFeeder.AutoFeed = true;

                    Console.WriteLine("Start Scanning Documents...");
                    _device.Acquire();

                    Console.Write("Press Enter when scanning is complete");
                    Console.ReadLine();

                    Console.WriteLine("Closing Scanner...");
                    _device.Close();
                    Console.WriteLine("  Closed");
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("  -------Exception:-------");
                Console.WriteLine(exception);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DirectInputGamepad"/> class.
 /// </summary>
 /// <param name="gamepadInstanceGuid">The gamepad instance GUID.</param>
 protected DirectInputGamepad(Guid gamepadInstanceGuid)
 {
     Device = new Device(gamepadInstanceGuid);
     Device.SetDataFormat(DeviceDataFormat.Joystick);
     Device.Acquire();
 }
        private void AddKeyboardDevices(IntPtr windowHandle)
        {
            DeviceList keyboardControllerList = Manager.GetDevices(DeviceClass.Keyboard, EnumDevicesFlags.AttachedOnly);
            for (int i = 0; i < keyboardControllerList.Count; i++)
            {
                keyboardControllerList.MoveNext();
                DeviceInstance deviceInstance = (DeviceInstance)keyboardControllerList.Current;

                Device device = new Device(deviceInstance.InstanceGuid);

                if (!CheckIfDirectInputDeviceExists(device))
                {
                    device.SetCooperativeLevel(windowHandle, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                    device.SetDataFormat(DeviceDataFormat.Keyboard);
                    device.Acquire();

                    KeyboardInput input = new KeyboardInput(device);
                    AddInputDevice(input);
                    input.InitCurrentlyInvokedInput();

                    InvokeNewInputDeviceEvent(input.DeviceInstanceId, input);
                }
            }
        }
        private void AddJoystickDevices(IntPtr windowHandle)
        {
            DeviceList gameControllerList = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
            for (int i = 0; i < gameControllerList.Count; i++)
            {
                gameControllerList.MoveNext();
                DeviceInstance deviceInstance = (DeviceInstance)gameControllerList.Current;

                Device device = new Device(deviceInstance.InstanceGuid);

                if (device.DeviceInformation.ProductGuid != new Guid("0306057e-0000-0000-0000-504944564944") &&       // Wiimotes are excluded
                    !CheckIfDirectInputDeviceExists(device))
                {
                    device.SetCooperativeLevel(windowHandle, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
                    device.SetDataFormat(DeviceDataFormat.Joystick);
                    device.Acquire();

                    JoystickInput input = new JoystickInput(device);
                    AddInputDevice(input);
                    input.InitCurrentlyInvokedInput();

                    InvokeNewInputDeviceEvent(input.DeviceInstanceId, input);
                }
            }
        }
        public void Acquire()
        {
            try
            {

                _device = new Device(Guid);
                _device.SetDataFormat(DeviceDataFormat.Mouse);
                _device.Properties.BufferSize = 16;
                _device.SetCooperativeLevel(Process.GetCurrentProcess().MainWindowHandle,
                    CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);

                _device.Acquire();
            }
            catch
            {
                Debug.Print("DirectInputMouse::Acquire exception");
                return;
            }
            _pollTimer.Change(0, POLL_INTERVAL);
            
            if (OnAcquire != null)
                OnAcquire(this, EventArgs.Empty);
        }
Beispiel #53
0
 // Функция инициализации джойстика
 public static void InitDevices()
 {
     joystick = null;
     // Поиск джойстика
     foreach (
         DeviceInstance di in
         Manager.GetDevices(
             DeviceClass.GameControl,
             EnumDevicesFlags.AttachedOnly))
     {
         joystick = new Device(di.InstanceGuid);
         break;
     }
     if (joystick != null)
     {
         // Установка диапазона осей на джойстике
         foreach (DeviceObjectInstance doi in joystick.Objects)
         {
             if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
             {
                 joystick.Properties.SetRange(
                     ParameterHow.ById,
                     doi.ObjectId,
                     new InputRange(-5000, 5000));
             }
         }
         // Установка абсолютного режима осей на джойстике
         joystick.Properties.AxisModeAbsolute = true;
         joystick.SetCooperativeLevel(
         f1,
         CooperativeLevelFlags.NonExclusive |
         CooperativeLevelFlags.Background);
         // Acquire devices for capturing (хз че это)
         joystick.Acquire();
         // Остановка таймера, запускающего инициализацию
         //f1.timer2.Stop();
         fm.timer_InitDevices.Stop();
         // Запуск таймера, проверяющего состояние джойстика
         //f1.timer1.Start();
         fm.timer_UpdateJoystick.Start();
         // Надпись "Joystick: online" и зеленая картинка внизу окна программы (в оконном режиме)
         fm.joystick_status.Text = "Joystick: online";
         Image img = Properties.Resources.online.ToBitmap();
         fm.joystick_status.Image = img;
         // Запись изменения в лог
         write_log("Joystick connected");
     }
 }
        public bool InitDevices()
        {
            //create joystick device.
            foreach (DeviceInstance di in Manager.GetDevices(
                DeviceClass.GameControl,
                EnumDevicesFlags.AttachedOnly))
            {
                mGamepad = new Device(di.InstanceGuid);
                break;
            }

            if (mGamepad == null)
            {
                //Throw exception if joystick not found.
                return false;
            }

            //Set joystick axis ranges.
            else
            {
                foreach (DeviceObjectInstance doi in mGamepad.Objects)
                {
                    if ((doi.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                    {
                        mGamepad.Properties.SetRange(
                            ParameterHow.ById,
                            doi.ObjectId,
                            new InputRange(-1000, 1000));
                    }

                }

                mGamepad.Properties.AxisModeAbsolute = true;
                mGamepad.SetCooperativeLevel(new WindowInteropHelper(System.Windows.Application.Current.MainWindow).Handle, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background);

                //Acquire devices for capturing.
                mGamepad.Acquire();
                mGamePadState = mGamepad.CurrentJoystickState;

            }

            mPollGamepadTimer.Tick += new EventHandler(GamePadUpdateTick);
            mPollGamepadTimer.Interval = TimeSpan.FromMilliseconds(100);
            mPollGamepadTimer.Start();

            return true;
        }
Beispiel #55
0
        public static void Init(System.Windows.Forms.Control targetControl)
        {
            if (_Mouse == null)
                _Mouse = new Mouse();
            if (_EmptyState == null)
                _EmptyState = new Mouse();
            _Device = new Device(SystemGuid.Mouse);
            _Device.SetCooperativeLevel(targetControl, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.NonExclusive);
            _Device.SetDataFormat(DeviceDataFormat.Mouse);
            targetControl.MouseMove += new MouseEventHandler(targetControl_MouseMove);

            try { _Device.Acquire(); }
            catch (DirectXException e) { Console.WriteLine(e.Message); }
        }
        public void Acquire()
        {
            try
            {
                _device = new Device(Guid);
                _device.SetDataFormat(DeviceDataFormat.Joystick);
                _device.Properties.BufferSize = 16;
                Debug.Print("Exclusive: {0} {1}", Name, _exclusive);
                _device.SetCooperativeLevel(Process.GetCurrentProcess().MainWindowHandle,
                   CooperativeLevelFlags.NonExclusive|CooperativeLevelFlags.Background);


                foreach (DeviceObjectInstance d in _device.Objects)
                {
                    if ((d.ObjectId & (int)DeviceObjectTypeFlags.Axis) != 0)
                        _device.Properties.SetRange(ParameterHow.ById, d.ObjectId, new InputRange(MinAxisValue, MaxAxisValue));
                }
                _device.Properties.AxisModeAbsolute = true;
                _device.Acquire();

                _pollTimer.Change(0, POLL_INTERVAL);
                Acquired = true;
                if (OnAcquire != null)
                    OnAcquire(this, EventArgs.Empty);
            }
            catch (OtherApplicationHasPriorityException)
            {
                Acquired = false;
                LastErrorMessage = Name + " couldn't be used in exclusive mode!";
                Debug.Print(LastErrorMessage);
                if (OnError != null)
                    OnError(this, EventArgs.Empty);

                return;
            }
            catch
            {
                Debug.Print("DirectInputJoystick::Acquire exception");
                LastErrorMessage = "DirectInput acquire error!";
                if (OnError != null)
                    OnError(this, EventArgs.Empty);
            }
        }
        private void AttachImpl(IntPtr window, CooperativeLevelFlags cooperativeLevelFlags)
        {
            if (this.running) {
                throw new InvalidOperationException("Already attached");
            }

            int index = 2;
            this.running = true;

            lock (this.syncRoot) {
                List<AutoResetEvent> resets = new List<AutoResetEvent>();
                foreach (DeviceInstance di in Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly)) {
                    AutoResetEvent reset = new AutoResetEvent(false);

                    var d = new Device(di.InstanceGuid);
                    d.Properties.BufferSize = 10;
                    d.SetCooperativeLevel(window, cooperativeLevelFlags);
                    d.SetDataFormat(DeviceDataFormat.Joystick);
                    d.SetEventNotification(reset);
                    d.Acquire();

                    resets.Add(reset);
                    this.joysticks.Add(di.InstanceGuid, d);
                    this.joystickIndexes.Add(index++, di.InstanceGuid);
                }

                this.waits = new AutoResetEvent[this.joysticks.Count + 2];
                this.waits[0] = new AutoResetEvent(false);
                this.keyboard = new Device(SystemGuid.Keyboard);
                this.keyboard.Properties.BufferSize = 10;
                this.keyboard.SetCooperativeLevel(window, cooperativeLevelFlags);
                this.keyboard.SetDataFormat(DeviceDataFormat.Keyboard);
                this.keyboard.SetEventNotification(this.waits[0]);
                this.keyboard.Acquire();

                this.waits[1] = new AutoResetEvent(false);
                this.mouse = new Device(SystemGuid.Mouse);
                this.mouse.Properties.BufferSize = 10;
                this.mouse.SetCooperativeLevel(window, cooperativeLevelFlags);
                this.mouse.SetDataFormat(DeviceDataFormat.Mouse);
                this.mouse.SetEventNotification(this.waits[1]);
                this.mouse.Acquire();

                resets.CopyTo(this.waits, 2);
            }

            (this.inputRunnerThread = new Thread(InputRunner) {
                Name = "DirectInput Runner",
                IsBackground = true
            }).Start();
        }
Beispiel #58
0
        public static void Init(System.Windows.Forms.Control targetControl)
        {
            if (_Keyboard == null)
                _Keyboard = new Keyboard();
            if (_EmptyState == null)
                _EmptyState = new Keyboard();
            _Device = new Device(SystemGuid.Keyboard);
            _Device.SetCooperativeLevel(targetControl, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.NonExclusive);
            _Device.SetDataFormat(DeviceDataFormat.Keyboard);

            Timer = new Timer();
            double InitTime = Timer.GetAbsoluteTime();
            for (int i = 0; i < _Keyboard.KeysElapsedTime.Length; i++)
                _Keyboard.KeysElapsedTime[i] = InitTime;

            try {_Device.Acquire();}
            catch (DirectXException e) { Console.WriteLine(e.Message); }
        }
        private void ensureGamepad()
        {
            if (m_gamepad == null)
            {
                int tryCnt = 3;
                while (m_gamepad == null && tryCnt-- > 0)
                {
                    try
                    {
                        DeviceList dl = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
                        foreach (DeviceInstance di in dl)
                        {
                            m_gamepad = new Device(di.InstanceGuid);
                            Tracer.Trace("GameControl device found: " + m_gamepad.DeviceInformation.ProductName + "  -  " + m_gamepad.DeviceInformation.InstanceName);
                            if (m_gamepad.DeviceInformation.ProductName.ToLower().IndexOf("rumble") >= 0)
                            {
                                //set cooperative level.
                                m_gamepad.SetCooperativeLevel(
                                    m_mainForm,
                                    CooperativeLevelFlags.Exclusive | CooperativeLevelFlags.Background);

                                //Set axis mode absolute.
                                m_gamepad.Properties.AxisModeAbsolute = true;

                                //Acquire joystick for capturing.
                                m_gamepad.Acquire();

                                string info = "Rumblepad: " + m_gamepad.DeviceInformation.InstanceName + "  state: " + m_gamepad.CurrentJoystickState;
                                Tracer.WriteLine(info);
                                break;
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        Tracer.Error(exc.ToString());
                        Thread.Sleep(1000);
                    }
                }

                if (m_gamepad == null)
                {
                    //Throw exception if gamepad not found.
                    throw new Exception("No gamepad found.");
                }
            }
        }
 protected static void AcquireDirectInputDevice(IntPtr windowHandle, Device device, DeviceDataFormat format)
 {
     device.SetCooperativeLevel(windowHandle, CooperativeLevelFlags.Background | CooperativeLevelFlags.NonExclusive);
     device.SetDataFormat(format);
     device.Acquire();
 }