简体   繁体   中英

Shared variable within event handlers C#

I've created a custom TextBox, with the ability to not accept input, when it's from an RFID reader (definied with HID ID). I have the HID ID, I have the two events, I have the property to set, but it's not working.

Here is the code:

public partial class STextBox : TextBox
{
    private RawInput _kblistener;
    private bool _handle = false;

    public STextBox()
    {
        _allowRfid = false;
        _kblistener = new RawInput(Handle, true);
        _kblistener.KeyPressed += _kblistener_KeyPressed;
    }

    private void _kblistener_KeyPressed(object sender, RawInputEventArg e)
    {
        if (e.KeyPressEvent.DeviceName == Config.RFIDreader) Handling = true;
        else Handling = false;
    }

    private bool Handling
    {
        get { return _handle; }
        set { _handle = value; }
    }

    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        e.Handled = Handling;
        base.OnKeyPress(e);
    }
}

The problem is: the first firing event is _kblistener_KeyPressed, and it sets Handling true if needed, but when the code gets to OnKeyPress, Handling is always false. I'm using RawInput_dll to get the HID ID.

All right. So thanks to Hans Passant, I figured out, that the problem were the non-static variables. After I changed _kblistener and _handle to static everything started working, as I expected.

Here is the working code:

public partial class STextBox : TextBox
{
    private bool _allowRfid;
    private static RawInput _kblistener;
    private static bool _handle = false;

    public STextBox()
    {
        _allowRfid = false;
        _kblistener = new RawInput(Handle, true);
        _kblistener.KeyPressed += _kblistener_KeyPressed;
    }

    private void _kblistener_KeyPressed(object sender, RawInputEventArg e)
    {
        if (e.KeyPressEvent.DeviceName == SetUp.RfidDevID) Handling = true;
        else Handling = false;
    }

    public bool AllowRFID
    {
        get { return _allowRfid; }
        set { _allowRfid = value; }
    }

    private static bool Handling
    {
        get { return _handle; }
        set { _handle = value; }
    }

    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if (!_allowRfid) e.Handled = Handling;
        base.OnKeyPress(e);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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