簡體   English   中英

如何使用 C# 導入 Windows 電源計划

[英]How to import a Windows Power Plan with C#

我正在開發一個小型 C# 應用程序,該應用程序會將電源計划導入用戶的 PC 並將其設置為活動狀態。 當 .pow 文件位於同一文件夾中並且我正在運行命令時,它與 .bat 文件完美配合:

powercfg -import "%~dp0\Optimized.pow"
powercfg /setactive 62ffd265-db94-4d48-bb7a-183c87641f85

現在,在 C# 我試過這個:

  Process cmd = new Process();
  cmd.StartInfo.FileName = "powercfg";
  cmd.StartInfo.Arguments = "-import \"%~dp0\\Optimized\"";
  cmd.StartInfo.Arguments = "powercfg /setactive 62ffd265-db94-4d48-bb7a-183c87641f85";
  cmd.Start(); 

  //and this:
  private void button1_Click(object sender, EventArgs e)
  {
      Process cmd = new Process();
      cmd.StartInfo.FileName = "cmd.exe";
      cmd.StartInfo.RedirectStandardInput = true;
      cmd.StartInfo.RedirectStandardOutput = true;
      cmd.StartInfo.CreateNoWindow = true;
      cmd.StartInfo.UseShellExecute = false;
      cmd.Start();
      cmd.StandardInput.WriteLine("powercfg -import \"%~dp0\\Optimized\"");
      cmd.StandardInput.WriteLine("powercfg /setactive 6aa8c469-317b-45d9-a69c-f24d53e3aff5");
      cmd.StandardInput.Flush();
      cmd.StandardInput.Close();
      cmd.WaitForExit();
      Console.WriteLine(cmd.StandardOutput.ReadToEnd());
  }

但是程序在項目文件夾中沒有看到.pow文件(我實際上嘗試將它放在項目中的每個文件夾中)。 如何實現讓 powercfg 看到文件?

任何幫助深表感謝! 謝謝!

你可以嘗試這樣的事情:

var cmd = new Process {StartInfo = {FileName = "powercfg"}};
using (cmd) //This is here because Process implements IDisposable
{

   var inputPath = Path.Combine(Environment.CurrentDirectory, "Optimized.pow");

   //This hides the resulting popup window
   cmd.StartInfo.CreateNoWindow = true;
   cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

   //Prepare a guid for this new import
   var guidString = Guid.NewGuid().ToString("D"); //Guid without braces

   //Import the new power plan
   cmd.StartInfo.Arguments = $"-import \"{inputPath}\" {guidString}";
   cmd.Start();

   //Set the new power plan as active
   cmd.StartInfo.Arguments = $"/setactive {guidString}";
   cmd.Start();
}

這修復了被覆蓋/使用兩次的Arguments參數,以及正確處理cmd變量。 添加了其他行以隱藏生成的彈出窗口 window,並用於預先生成 Guid 並將其指定為命令行的一部分。

您的第一個片段不起作用,因為您在執行該過程之前要重新分配cmd.StartInfo.Arguments 當您將第一個作業扔掉以支持第二個作業時,它就會丟失。

第一個片段很可能不起作用,因為當您將cmd.startInfo.FileName設置為沒有路徑的文件名時,它只會搜索 C# 應用程序的.exe 的目錄(可能在project/bin/Debug/中)。 由於文件名是cmd.exe並且您的項目文件夾中可能沒有cmd.exe ,因此它找不到任何內容。

您還可以考慮將cmd.StartInfo.WorkingDirectory設置為包含.pow文件的適當目錄,以便您的相對路徑能夠正確解析。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM