0

I build mouse and keyboard recorder for my program. I write all user events and save in serializable object. Information about mouse and keyboard events I get from other program part with protected fields.

That's why for getting values I use reflection like this:

foreach (var item in events)
{
    // Get all protected fields by reflection for EventArgs. 
    var allProps = item.EventArgs.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).OrderBy(pi => pi.Name).ToList();
}

After this I saved all in serialized object like this.

string MouseButton = Convert.ToString(allProps[0].GetValue(item.EventArgs));

But now I found out, that I should use mouse and keyboard simulator. It works fine, but works only with enum MouseButton and Key types. (something like this)

public enum MouseButton
{
    Left = 0x2,
    Right = 0x8,
    Middle = 0x20
}

public static void MouseDown(MouseButtons button)
{
    switch (button)
    {
        case MouseButtons.Left:
            MouseDown(MouseButton.Left);
            break;
        case MouseButtons.Middle:
            MouseDown(MouseButton.Middle);
            break;
        case MouseButtons.Right:
            MouseDown(MouseButton.Right);
            break;
    }
}

How I can convert my string MouseButton type to enum MouseButton type for mouse simulator?

P.S. i tried get right type for allProps, but it always return object type for me, not real events type.

Denis Savenko
  • 829
  • 1
  • 13
  • 29
  • Thank you for note. I ```Enym.TryParse```, but sometimes ```allProps[0].GetValue(item.EventArgs)``` equal to ```null``` and parse can't convert ```bool``` to ```string```. I tried different wrapper if end etc for ```null``` chacked, but can't build program with this type problem( – Denis Savenko Jun 30 '20 at 11:40

1 Answers1

1

I think that you will want to use the Enum.Parse function to convert your string MouseButton name into the associated enum value. This will generate an enum value matching the string provided to the name of the vaule.

string mouseButtonVal = Convert.ToString(allProps[0].GetValue(item.EventArgs));
MouseButton button = (MouseButton) Enum.Parse(typeof(MouseButton), mouseButtonVal);
Simona
  • 279
  • 1
  • 8