繁体   English   中英

修改传递给事件处理程序的结构?

[英]Modifying a struct passed to an event handler?

这似乎是一个我不明白的基本概念。

在为键盘驱动程序编写.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);
}

Stroke是一个struct ,它包含按下的键的扫描码和状态。

在上面的代码中,由于我通过引用传递值类型结构,所以对结构进行的任何更改都将在传递给操作系统时被“记住”(这样可以拦截和修改按下的键)。 所以没关系。

但是如何让我的OnKeyPressed事件的订阅者修改struct Stroke

以下不起作用:

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
    }
}

提前致谢。

像这样的东西可以做到这一点:

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

为您的订阅者提供一份副本,然后在完成后将其复制回本地值。

或者,您可以创建自己的类来表示击键并将其传递给订阅者吗?

在KeyPressedEventArg的构造函数中传递结构是通过引用传递的,但就是这样,只要修改了描边变量,它就会通过值传递。 如果你继续通过ref传递这个结构,你可能要考虑为它创建一个包装类。 从长远来看,更好的设计决策。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM