C# Winforms 根据 运行 进程更改标签

C# Winforms change label based on running process

我在 Visual Studio 2008 年用 C# 开发了一个 dotnet 2.0 应用程序,它非常简单:

APP

当我的进程 loop.exe 正在 运行ning 或停止时,我想将当前名为 "label1" 的标签名称更改为 "Running" 或 "Stopped"。

当我按下开始时,它会 运行 loop.exe 并且停止按钮显然会停止它。

我已经阅读了很多关于 C# Winforms 的主题,但我无法让它正常工作,我不知道现在该怎么做。我想我需要添加一个 backgroundworker,但我不知道如何检查进程并以编程方式更新标签。

这是我的 clean/current 代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;

namespace APP_NAME
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Start_Click(object sender, EventArgs e)
        {
            Process.Start("loop.exe");

        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Process.Start("taskkill", "/F /IM loop.exe");
            Process.Start("taskkill", "/F /IM azcopy.exe");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Process.Start("notepad.exe", @"C:\ProgramData\APP_NAME\settings\settings.xml");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", @"C:\ProgramData\APP_NAME\logs");
        }

    }
}

希望我说清楚了,谢谢。

您可以通过访问 Text 属性 来更新标签显示的文本。因此,将您的方法更改为:

private void Start_Click(object sender, EventArgs e)
{
    Process.Start("loop.exe");
    label1.Text = "Running";
}