This seems to be a pretty basic concept that I don’t understand.
In writing a .NET wrapper for a keyboard driver, I’m broadcasting an event for each key pressed, like so (simplified code below):
// 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 is a struct which contains the scancode for the pressed key, and a state.
In the above code, since I’m passing the value-type structure by reference, any changes made to the struct will be ‘remembered’ when passed to the OS (so that pressed keys may be intercepted and modified). So that’s fine.
But how do I let subscribers to my OnKeyPressed event modify the struct Stroke?
The following doesn’t work:
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
}
}
Thanks in advance.
Something like this may do the trick:
Give your subscriber a copy and then copy it back to your local value once they’re done with it.
Alternatively, can you create your own class representing a keystroke and pass that to the subscriber?