我正在尝试使用按钮单击事件杀死notepad.exe。

由于process.WaitForExit();,它必须在线程中。

现在,单击按钮根本不执行任何操作,无法弄清原因。

在此先感谢您的帮助 :)

这是我当前的代码:

using System.Windows;
using System.Threading;
using System.Diagnostics;


namespace WpfApp5
{
    public partial class MainWindow : Window
    {
        Thread mythread = new Thread(() =>
        {
            Process process = new Process();
            process.StartInfo.FileName = @"notepad.exe";
            process.Start();
            process.WaitForExit();
        });

        public MainWindow()
        {
            InitializeComponent();
            mythread.Start();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            mythread.Abort();
        }
    }
}

最佳答案

只需对代码进行最少的更改,即可按以下方式进行操作,

public partial class MainWindow : Window
{
    static Process process; //making process class level member;
    Thread mythread = new Thread(() =>
    {
        process = new Process();
        process.StartInfo.FileName = @"notepad.exe";
        process.Start();
    });

    public MainWindow()
    {
        InitializeComponent();
        mythread.Start();
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        process.Kill(); //killing the actual process.
        mythread.Abort();
    }
}

关于c# - C#-从button_click杀死线程进程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50284200/

10-13 04:16