【问题标题】:Execute shell with custom command使用自定义命令执行 shell
【发布时间】:2014-01-08 09:53:56
【问题描述】:

我只是想在 Windows 7 机器上使用 C# 执行 shell 命令。

我在网上找到了这个 sn-p:

[DllImport("shell32.dll", EntryPoint = "ShellExecute")]
public static extern long ShellExecute(int hwnd, string cmd, string file, string param1, string param2, int swmode);

void exe()
{
    ShellExecute (0, "open", "C:\WINDOWS\Zapotec.bmp", "", "", 5)
}

这很好用,但我不想打开它,我想执行一个自定义命令(来自第三方应用程序)。具体:我想使用没有命令行界面的病毒扫描程序进行病毒扫描(可以在 Windows 资源管理器的上下文菜单中启动)。

有什么建议吗?我没有在互联网上找到任何有用的信息。 它不必是 C# 解决方案。它也可以是一个外部文件(我发现程序“runmenu”[http://www.programbits.co.uk/downloads/runmenu.zip],它应该可以完美解决这个问题,但不幸的是并非所有上下文菜单项都受支持)。

更新

我刚刚使用 powershell 找到了解决问题的方法:

PS C:\temp> $o = new-object -com Shell.Application
PS C:\temp> $folder = $o.NameSpace("C:\temp")
PS C:\temp> $file=$folder.ParseName("test.txt")
PS C:\temp> $file.Verbs() | select Name
PS C:\temp> $file.Verbs() | %{ if($_.Name -eq 'Edit with &Notepad++') { $_.DoIt() } }

enter link description here

【问题讨论】:

标签: c# windows shell contextmenu explorer


【解决方案1】:

试试这个:

using System.Diagnostics;

private void runCom(string command)
{
    ProcessStartInfo procInfo = new ProcessStartInfo("cmd", "/c" + command);
    startInfo.UseShellExecute = false;
    startInfo.CreateNoWindow = true;
    Process proc = new Process();
    proc.StartInfo = startInfo;
    proc.Start();
    proc.WaitForExit();
}

【讨论】:

  • 感谢您的回复。但是我怎么能只执行一个shell命令(Windows资源管理器中的上下文菜单条目)。你的代码只是运行一个带参数的可执行文件?
【解决方案2】:

你能不使用 Process.Start() 吗?

您可以根据需要使用 ProcessStartInfo 重载来发送参数。

在 System.Diagnostics 命名空间中找到。

【讨论】:

    【解决方案3】:

    正如 Jason 已经建议的那样,
    查看 .NET Framework 的 System.Diagnostics 命名空间。它用于调用 Process 。

    您可以将 ProcessStartInfo 的 useShellExecute 属性设置为 true ;抑制窗口生成,.

    【讨论】:

      【解决方案4】:

      最好使用System.Diagnostics.Process类(MSDN)。

      【讨论】:

      • @user2445254 请不要通过编辑将新问题添加到答案中。使用 cmets 向答案的作者提问。
      • 对此我很抱歉,我想添加一条评论 - 注意力不集中;)抱歉。
      猜你喜欢
      • 2013-01-05
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 2023-03-18
      • 2018-10-06
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多