开发者

C#: Running a process on button click

开发者 https://www.devze.com 2023-03-09 04:59 出处:网络
I am running a process on button click of my WPF application as shown below: private void btnGetValues_Click(object sender, RoutedEventArgs e)

I am running a process on button click of my WPF application as shown below:

private void btnGetValues_Click(object sender, RoutedEventArgs e)
{
    string arg1 = "1";
    Process p1 = new Process();
    p1.StartInfo.CreateNoWindow = true;
    p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    p1.StartInfo.FileName = "myexe.exe";
    p1.StartInfo.Arguments = arg1;
    p1.StartInfo.UseShellExecute = false;
    p1.StartInfo.RedirectStandardOutput = true;
    p1.StartInfo.RedirectStandardInput = true;
    p1.StartInfo.RedirectStandardError = true;
    p1开发者_开发百科.Start();

    //while (!p1.HasExited)
    //{

    //}

    MessageBox.Show(p1.StandardOutput.ReadToEnd());
}

The problem is that even after the process executes, the button continues to remain in clicked state. What could be the problem?


Why do you need the last message box? get read of it and it should work. If you are still experiencing problems then you can run it in a separate thread. That is a way of executing multiple things at the same time. here is an example.

Edit

sorry I understood the wrong thing. You can set the focus to something else if you wish the button to lose that appearance.

private void button1_Click(object sender, EventArgs e)
        {
            string arg1 = "1";
            Process p1 = new Process();
            p1.StartInfo.CreateNoWindow = true;
            p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p1.StartInfo.FileName = @"yourExecutable";
            p1.StartInfo.Arguments = arg1;
            p1.StartInfo.UseShellExecute = false;
            p1.StartInfo.RedirectStandardOutput = true;
            p1.StartInfo.RedirectStandardInput = true;
            p1.StartInfo.RedirectStandardError = true;
            p1.Start();
            //while (!p1.HasExited)
            //{

            // }

            MessageBox.Show(p1.StandardOutput.ReadToEnd());

            button2.Focus();  // set button 2 to have a height of 0 so it is not visible
            // or place it somewhere where it cannot be seen



        }
0

精彩评论

暂无评论...
验证码 换一张
取 消