2012-03-12 58 views
0

這似乎是一個我不明白的基本概念。修改傳遞給事件處理程序的結構體?

在寫一個.NET包裝的鍵盤驅動程序,我在廣播每個鍵的按下事件,像這樣(下面簡化代碼):

// The event handler applications can subscribe to on each key press 
public event EventHandler<KeyPressedEventArgs> OnKeyPressed; 
// I believe this is the only instance that exists, and we just keep passing this around 
Stroke stroke = new Stroke(); 

private void DriverCallback(ref Stroke stroke...) 
{ 
    if (OnKeyPressed != null) 
    { 
     // Give the subscriber a chance to process/modify the keystroke 
     OnKeyPressed(this, new KeyPressedEventArgs(ref stroke)); 
    } 

    // Forward the keystroke to the OS 
    InterceptionDriver.Send(context, device, ref stroke, 1); 
} 

中風是一種struct其中包含了掃描碼按下的鍵和狀態。

在上面的代碼中,因爲我通過引用傳遞值類型結構,所以對結構進行的任何更改都會在傳遞給操作系統時被「記住」(以便按下的鍵可能會被攔截和修改)。這很好。

但我該如何讓訂閱者對我的OnKeyPressed事件修改structStroke

下不起作用:

public class KeyPressedEventArgs : EventArgs 
{ 
    // I thought making it a nullable type might also make it a reference type..? 
    public Stroke? stroke; 

    public KeyPressedEventArgs(ref Stroke stroke) 
    { 
     this.stroke = stroke; 
    } 
} 

// Other application modifying the keystroke 

void interceptor_OnKeyPressed(object sender, KeyPressedEventArgs e) 
{ 
    if (e.stroke.Value.Key.Code == 0x3f) // if pressed key is F5 
    { 
     // Doesn't really modify the struct I want because it's a value-type copy? 
     e.stroke.Value.Key.Code = 0x3c; // change the key to F2 
    } 
} 

在此先感謝。

+0

使'stroke'爲空可以將你的實際值放入一個包含指示值是否存在的布爾值的包裝器中。包裝值從一開始就是一個值類型。 – 2012-03-12 04:24:55

+1

除了@ EricJ。的評論,可以爲null的類型本身也是值類型,儘管值類型從編譯器中獲得了很多特殊的處理。 – phoog 2012-03-13 04:43:45

回答

1

像這樣的事情可以做的伎倆:

if (OnKeyPressed != null)  
{   
    // Give the subscriber a chance to process/modify the keystroke   
    var args = new KeyPressedEventArgs(stroke); 
    OnKeyPressed(this, args);  
    stroke = args.Stroke; 
} 

給你的用戶的副本,然後將其複製回本地值一旦他們用它做。

或者,您可以創建自己的代表擊鍵的類並將其傳遞給用戶?

+0

完美地工作,對於簡單的問題抱歉。 – Jason 2012-03-12 05:08:48

1

在KeyPressedEventArg的構造函數中傳遞你的結構體是通過引用傳遞的,但那就是它,任何時候中風變量被修改它都是通過值傳遞的。如果你不斷傳遞這個結構體,你可能會考慮爲它創建一個包裝類。長遠來看,更好的設計決策。

相關問題