2013-08-24 56 views
0

我是C#和Sharpdx的新手。我有幾天這個代碼問題,我不明白方式不起作用!這是一個簡單的任務,即獲取遊戲杆的一個軸的值​​並將其顯示在窗體的文本框中。用SharpDX收購遊戲杆

我做了一個關於Visual Studio 2010 express的新項目,我做了一個帶有按鈕和文本框的窗體,用於顯示操縱桿軸(X軸)的值。

下面的代碼的第一部分是sharpdx文檔中的例子,第二部分有點不同。

的問題是該值不會改變我每次按下按鈕時

有些事情不對,但我不知道是什麼

private void button3_Click(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.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 e stato 
    Joystick joystick = new Joystick(directInput, joystickGuid); 
    JoystickState stato = new JoystickState(); 

    // specifico se relativo o assoluto 
    joystick.Properties.AxisMode = DeviceAxisMode.Absolute; 

    // effettuo un collegamento con il joystick 
    joystick.Acquire(); 

    // qui faccio una acquisizione dello stato che memorizzo 
    joystick.Poll(); 

    // effettuo una lettura dello stato 
    joystick.GetCurrentState(ref stato); 

    // stampo il valore dell'ordinata 
    textBox1.Text = stato.X.ToString(); 
} 

回答

2

我認爲問題是,你在呼喚PollGetCurrentState - 你只需要做一個或另一個。

從你的問題,它聽起來像後者 - 這是你想按GetCurrentState當按鈕被按下 - 而不是Poll循環中的變化。

如果你確實想獲得當前狀態,那麼你想要這樣的東西。

var directInput = new DirectInput(); 
var joystickState = new JoystickState(); 
var joystick = new Joystick(directInput, joystickGuid); 
joystick.Acquire(); 
joystick.GetCurrentState(ref joystickState); 
textBox1.Text = joystickState.X.ToString(); 

如果你想調查你想要的東西這樣的變化。

var directInput = new DirectInput(); 
var joystick = new Joystick(directInput, joystickGuid); 
joystick.Acquire(); 
joystick.Properties.BufferSize = 128; 
while (true) 
{ 
    joystick.Poll(); 
    var data = joystick.GetBufferedData(); 
    foreach (var state in data) 
    { 
    if (state.Offset == JoystickOffset.X) 
    { 
     textBox1.Text = state.Value; 
    } 
    } 
}