ContextMenu保持第一个计划

时间:2018-02-02 07:40:14

标签: c# winforms contextmenu

我有一个正常工作的上下文菜单,除了在一种情况下: 当我想执行一个进程时,上下文菜单保留在第一个计划中,因此使用我打开的应用程序会产生干扰,也许这是因为我在等待进程完成?

以下是我为启动过程打开的WindowForm的代码:

public Process process { get; set; }
        public string A { get; set; }
        public string B { get; set; }
        public bool finished { get; set; }
        public ExecuteProcess(string a, string b,string entete,string message)
        {
            InitializeComponent();
            this.process = new Process();
            this.A = a;
            this.B = b;
            this.Text = entete;
            this.label1.Text = message;
            finished = false;          
        }
        private void ExecuteProcess_Shown(object sender, EventArgs e)
        {
            try
            {
                ProcessStartInfo Install332 = new ProcessStartInfo();
                Install332.FileName = this.A;
                Install332.Arguments = this.B;
                this.process = Process.Start(Install332);
                this.process.WaitForExit();
                this.finished = true;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "");
            }
        }

        private void ExecuteProcess_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(!this.finished)
            {
                e.Cancel = true;
            }
        }

我打开一个WindowForm,它会显示所需的消息,启动进程,并保持打开直到进程完成。我有两种情况:

1)我执行一个应用程序,因此它打开一个新窗口,但上下文菜单保留在第一个计划中。

2)我执行外部基本文件,WindowForm出现,直到进程结束。

我也放了一个prinscreen,以防它有任何帮助:

Context stay on front

编辑:也许有用的信息,上下文菜单是在ListView(WPF)中定义的

1 个答案:

答案 0 :(得分:0)

简单地说,使用任务......

    private async void ExecuteProcess_Shown(object sender, EventArgs e)
    {
        var errorMessage = await Task.Run(() =>
        {
            var exceptionMessage = string.Empty;
            try
            {
                ProcessStartInfo Install332 = new ProcessStartInfo();
                Install332.FileName = this.A;
                Install332.Arguments = this.B;
                this.process = Process.Start(Install332);
                this.process.WaitForExit();
                this.finished = true;
                this.Close();
            }
            catch (Exception ex)
            {
                exceptionMessage = ex.Message;
            }

            return exceptionMessage;
        });

        if (!string.IsNullOrEmpty(errorMessage))
        {
            MessageBox.Show(errorMessage);
        }
    }

看起来之前有人问过:WPF ContextMenu still visible after launching an external process