通用游戏手柄协议解析Joystick - 清修客

时间:2024-02-18 17:25:32

通用游戏手柄协议解析Joystick

微软出品通用游戏手柄按键解析

1. 引用SharpDX.DirectInput.dll(可以通过NuGet包管理安装),该dll包含获取接入设备的信息,接入设备的输入等

2. 创建DirectInput,并获取Joystick对象

 1 Joystick pad;
 2 
 3 private void GetJoyStick()
 4         {
 5             var directInput = new DirectInput();
 6             var joysticGuid = Guid.Empty;
 7             foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices))
 8                 joysticGuid = deviceInstance.InstanceGuid;
 9 
10             if (joysticGuid == Guid.Empty)
11                 foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick, DeviceEnumerationFlags.AllDevices))
12                     joysticGuid = deviceInstance.InstanceGuid;
13             if (joysticGuid == Guid.Empty)
14             {
15                 MessageBox.Show("未连接摇杆!");
16                 Environment.Exit(1);
17             }
18 
19             StringBuilder sb = new StringBuilder();
20             pad = new Joystick(directInput, joysticGuid);
21             var allEffects = pad.GetEffects();
22             foreach (var effectInfo in allEffects)
23                 sb.Append(effectInfo.Name.ToString());
24 
25             StringBuilder sb1 = new StringBuilder();
26             pad.Properties.BufferSize = 128;
27             pad.Acquire();
28         }
View Code

3. 实现获取手柄位移、按键输入的方法

 1 private void GetJoyStickDatas(object sender, EventArgs e)
 2         {
 3             JoystickState state = new JoystickState();
 4 
 5             state = pad.GetCurrentState();
 6 
 7             txt1.Text = state.X.ToString();
 8             txt2.Text = state.Y.ToString();
 9             txt3.Text = state.Z.ToString();
10             txt4.Text = state.AccelerationX.ToString();
11             bool[] buttons = state.Buttons;
12             int clickedId = 0;
13             foreach(bool item in buttons)
14             {
15                 clickedId++;
16                 if (item)
17                     buttonClickTXT.Text = clickedId + " is clicked";
18             }
19         }
View Code

4. 通过定时器定时获取Joystick对象的输入

1 DispatcherTimer m_tmrHistory;
2 
3         private void myJoyStick_Loaded(object sender, RoutedEventArgs e)
4         {
5             m_tmrHistory = new DispatcherTimer();
6             m_tmrHistory.Interval = TimeSpan.FromSeconds(0.1);
7             m_tmrHistory.Tick += GetJoyStickDatas;
8             m_tmrHistory.Start();
9         }
View Code