启动外部进程后,WPF ContextMenu仍然可见 [英] WPF ContextMenu still visible after launching an external process
问题描述
我正在从ContextMenu启动外部应用程序,并且必须在目标应用程序运行时阻止源应用程序。为此,我使用 Process.WaitForExit()
来避免源应用程序对事件做出响应。
I'm launching an external application from a ContextMenu, and I must block the the source application while the target application is running. To achieve this I'm using Process.WaitForExit()
to avoid the source application responding to events.
问题是上下文菜单仍在目标应用程序的前面。让我们用一个简单的示例查看它:
The problem is the context menu is still ahead the target application. Let's see it with a simple example:
这是我在示例中使用的代码。
This is the code I'm using for the example.
public MainWindow()
{
InitializeComponent();
this.ContextMenu = new ContextMenu();
MenuItem menuItem1 = new MenuItem();
menuItem1.Header = "Launch notepad";
menuItem1.Click += MyMenuItem_Click;
this.ContextMenu.Items.Add(menuItem1);
}
void MyMenuItem_Click(object sender, RoutedEventArgs e)
{
Process p = new Process();
p.StartInfo.FileName = "notepad.exe";
p.StartInfo.CreateNoWindow = false;
p.Start();
p.WaitForExit();
p.Close();
}
如何在显示目标应用程序之前使ContextMenu消失? / p>
How could I make the ContextMenu to disappear before the target application is displayed?
推荐答案
基于 Jcl ...
我找到了一个使用自定义MenuItems菜单的简单解决方案。它会延迟 MenuItem.Click()
事件,直到父 ContextMenu
关闭。
I found a simple solution using custom MenuItems for the menu. It delays the MenuItem.Click()
event until the parent ContextMenu
is closed.
class MyMenuItem : MenuItem
{
protected override void OnClick()
{
ContextMenu parentContextMenu = Parent as ContextMenu;
parentContextMenu.Closed += ContextMenu_Closed;
parentContextMenu.IsOpen = false;
}
void ContextMenu_Closed(object sender, RoutedEventArgs e)
{
ContextMenu parent = Parent as ContextMenu;
parent.Closed -= ContextMenu_Closed;
base.OnClick();
}
}
这篇关于启动外部进程后,WPF ContextMenu仍然可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!