Home > Software engineering >  WPF - problem when invoking System.Windows.Forms.SendKeys.Send("{ESC}")
WPF - problem when invoking System.Windows.Forms.SendKeys.Send("{ESC}")

Time:09-22

In my Autodesk Revit plugin, I have a modeless WPF window opened on top of Revit. On that window, I have a checkbox that decides on the selection mode in Revit app. Each time the mode is toggled on the checkbox I need to send the "ESC" key to Revit so that it cancels the current mode and enters the other mode (Revit throws an exception when ESC is sent, I invoke the other mode from catch statement recursively)".

Here is the current code:

<CheckBox IsChecked="{Binding Path=IsMultiselection}" Checked="multiselection_chk_Checked" Unchecked="multiselection_chk_UnChecked">
private void multiselection_chk_Checked(object sender, RoutedEventArgs e)
{
    MultiselectChanged = true;

    ActivateRevitWindow();
    System.Windows.Forms.SendKeys.Send("{ESC}");
}

private void multiselection_chk_UnChecked(object sender, RoutedEventArgs e)
{
    MultiselectChanged = true;

    ActivateRevitWindow();
    System.Windows.Forms.SendKeys.Send("{ESC}");
}
public class ViewModel : INotifyPropertyChanged
{
    private bool _isMultiselection;
    public bool IsMultiselection
    {
        get => _isMultiselection;
        set
        {
            _isMultiselection = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

The problem I'm currently facing is that although the selection mode is toggled correctly in Revit the UI of my window is not updating - the checkbox is constantly unchecked. I noticed that if I put any code after System.Windows.Forms.SendKeys.Send("{ESC}"); it won't be reached while I'm debugging if I comment out this line the UI is working fine but the selection mode won't toggle in Revit.

Any ideas of how to fix this already whacky solution?

CodePudding user response:

Eventually I fixed this issue by replacing System.Windows.Forms.SendKeys.Send("{ESC}"); with following code:

[DllImport("user32.dll", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, int Msg, System.Windows.Forms.Keys wParam, IntPtr lParam);

const int WM_KEYDOWN = 0x0100;

public void PressEsc()
{
    PostMessage(RevitWindowHandle, WM_KEYDOWN, System.Windows.Forms.Keys.Escape, IntPtr.Zero);
}

Inspiration came from this answer.

  • Related