為了提高炒股軟件同花順的運行速度,消除卡頓,編寫一個C#程序,來設置同花順進程的優先級。
using System;
using System.Diagnostics;
using System.Security.Principal;namespace ProcessPrioritySetter
{class Program{static void Main(string[] args){// 請求管理員權限(必需)if (!IsRunningAsAdmin()){Console.WriteLine("請以管理員身份重新運行此程序!");RestartAsAdmin();return;}// 1. 設置當前運行的 hexin.exe 進程優先級SetExistingProcessPriority();2. 創建計劃任務實現永久生效//CreateScheduledTask();//Console.WriteLine("已成功設置優先級并創建永久任務!");//Console.ReadKey();// 5秒倒計時后自動關閉Console.WriteLine("操作已完成,程序將在5秒后自動關閉...");for (int i = 5; i > 0; i--){Console.Write($"\r倒計時: {i}秒 "); // 使用\r實現原地更新System.Threading.Thread.Sleep(1000); // 等待1秒}Console.WriteLine("\n程序關閉!");}// 設置現有進程優先級static void SetExistingProcessPriority(){Process[] processes = Process.GetProcessesByName("hexin");if (processes.Length == 0){Console.WriteLine("未找到 hexin.exe 進程,請在程序運行后執行此操作");return;}foreach (Process proc in processes){try{proc.PriorityClass = ProcessPriorityClass.High;Console.WriteLine($"已設置進程 {proc.Id} 優先級為高");}catch (Exception ex){Console.WriteLine($"設置進程優先級失敗: {ex.Message}");}}}// 創建計劃任務static void CreateScheduledTask(){try{// 使用 schtasks 命令創建任務ProcessStartInfo psi = new ProcessStartInfo{FileName = "schtasks",Arguments = "/Create /TN \"HexinHighPriority\" /XML \"priority_task.xml\" /F",UseShellExecute = false,CreateNoWindow = true};// 生成 XML 任務描述文件System.IO.File.WriteAllText("priority_task.xml", GetTaskXmlContent());Process.Start(psi)?.WaitForExit();Console.WriteLine("計劃任務創建成功!");}catch (Exception ex){Console.WriteLine($"創建計劃任務失敗: {ex.Message}");}}// 管理員權限檢查static bool IsRunningAsAdmin(){return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);}// 重新以管理員身份啟動static void RestartAsAdmin(){ProcessStartInfo startInfo = new ProcessStartInfo{FileName = Process.GetCurrentProcess().MainModule.FileName,UseShellExecute = true,Verb = "runas"};Process.Start(startInfo);}// 獲取計劃任務 XML 內容static string GetTaskXmlContent(){return @"<?xml version='1.0' encoding='UTF-16'?>
<Task version='1.4' xmlns='http://schemas.microsoft.com/windows/2004/02/mit/task'><RegistrationInfo><Description>設置 hexin.exe 進程為高優先級</Description></RegistrationInfo><Triggers><LogonTrigger><Enabled>true</Enabled></LogonTrigger></Triggers><Principals><Principal id='Author'><RunLevel>HighestAvailable</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><IdleSettings><StopOnIdleEnd>false</StopOnIdleEnd></IdleSettings></Settings><Actions Context='Author'><Exec><Command>cmd.exe</Command><Arguments>/c wmic process where name='hexin.exe' call setpriority 'high priority'</Arguments></Exec></Actions>
</Task>";}}
}