CSGO进程检测代码标签文本不更新问题求助
CSGO进程检测标签文本不更新问题排查与修复
问题描述
编写了检测CSGO是否运行的代码,将HookGame函数绑定到间隔5000ms的timer3_Tick事件,窗体加载时启动timer3。目前启动CSGO时timer2能正常启动,但label4的文本始终不变化。
原代码如下:
HookGame函数
public void HookGame() { Process[] processList = Process.GetProcesses(); foreach (Process process in processList) { label2.Dispose(); label3.Show(); if (process.ProcessName.Contains("csgo")) { timer2.Start(); label4.Text = "Csgo is running"; this.label4.Location = new System.Drawing.Point(label4.Left = (this.Width - label4.Width), 200); label4.Show(); } else { label4.Text = "Csgo is not running"; this.label4.Location = new System.Drawing.Point(label4.Left = (this.Width - label4.Width), 200); Refresh(); label4.Show(); } } }
timer3_Tick事件
private void timer3_Tick(object sender, EventArgs e) { HookGame(); }
问题分析
- 遍历逻辑错误:遍历所有进程时,每遇到一个非csgo进程,就会把label4的文本重置为“Csgo is not running”,哪怕之前已经检测到csgo进程。这会导致即使CSGO在运行,只要有其他进程存在,最终标签文本会被覆盖为未运行状态。
- 冗余控件操作:循环内重复调用
label4.Location设置、label4.Show()完全没必要;调用label2.Dispose()会直接销毁该控件,后续无法再使用,属于错误操作。 - 刷新时机错误:
Refresh()调用位置不对,且逻辑错误导致文本被覆盖,刷新也无法解决问题。
修复方案
调整逻辑:先判断系统中是否存在csgo进程,再统一更新标签文本,移除不必要的控件操作。
修正后的代码:
HookGame函数
using System.Linq; // 需要引入LINQ命名空间 public void HookGame() { // 先判断是否存在csgo进程,忽略大小写避免匹配问题 bool isCsgoRunning = Process.GetProcesses() .Any(p => p.ProcessName.IndexOf("csgo", StringComparison.OrdinalIgnoreCase) >= 0); label3.Show(); // 若后续还需使用label2,替换为label2.Hide(),不要调用Dispose()销毁控件 // label2.Hide(); if (isCsgoRunning) { timer2.Start(); label4.Text = "Csgo is running"; } else { timer2.Stop(); // 可选:CSGO未运行时停止timer2 label4.Text = "Csgo is not running"; } // 位置设置只执行一次即可 label4.Location = new System.Drawing.Point((this.Width - label4.Width), 200); label4.Show(); // 强制刷新标签确保文本更新 label4.Refresh(); }
关键修改点
- 使用LINQ的
Any方法直接判断是否存在csgo进程,避免遍历过程中反复覆盖标签文本。 - 移除循环内的冗余控件操作,将位置设置和显示操作移到判断逻辑之后,只执行一次。
- 增加对timer2的停止逻辑(可选),确保CSGO未运行时timer2不会持续运行。
- 进程名判断忽略大小写,兼容不同大小写的进程名情况。
- 移除
label2.Dispose(),改用Hide()(若需隐藏)避免控件被永久销毁。
内容的提问来源于stack exchange,提问作者Mert
相关产品推荐
相关产品推荐

