注册CMD提示上下文菜单

时间:2018-06-26 12:01:49

标签: c# console contextmenu

我正在注册一个上下文菜单命令来产生文件的哈希值。我遇到的问题是已注册的命令无法将命令提示符窗口的结果显示在视图中。当我右键单击并调用“创建哈希”时,结果将短暂闪烁,然后关闭。即使在下面添加pause也不会使结果可见。我需要添加任何注册表项来防止窗口关闭吗?

static void Main(string[] args)
{
    string menuCommand = "CertUtil -hashfile \"%1\" pause";
    Register("*", "HashFile", "Create Hash", menuCommand);
}
public static void Register(
    string fileType, string shellKeyName,
    string menuText, string menuCommand)
{
    if (string.IsNullOrEmpty(fileType) ||
        string.IsNullOrEmpty(shellKeyName) ||
        string.IsNullOrEmpty(menuText) ||
        string.IsNullOrEmpty(menuCommand))
        return;

    string regPath = string.Format(@"{0}\shell\{1}", fileType, shellKeyName);

    using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(regPath))
    {
        key.SetValue(null, menuText);
    }

    using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(
        string.Format(@"{0}\command", regPath)))
    {
        key.SetValue(null, menuCommand);
    }
}

1 个答案:

答案 0 :(得分:1)

一种快速简便的解决方案是通过您自己的控制台应用程序包装public class SessionExpired : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { //My Code to handle the session event base.OnActionExecuted(actionExecutedContext); } } ,并将其添加到注册表中,而不是直接运行CertUtil的。

让我们说下面的代码用于CertUtil

CertUtilWrapper

然后将代码更改为

static void Main(string[] args)
{
    var proc = new Process 
    {
        StartInfo = new ProcessStartInfo 
        {
            FileName = "CertUtil.exe",
            Arguments = string.Join(" ", args)
            UseShellExecute = false,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            CreateNoWindow = true
        }
    }.Start();
    Console.WriteLine(proc.StandardOutput.ReadToEnd());
    Console.WriteLine(proc.StandardError.ReadToEnd());
    proc.WaitForExit();
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
};

很明显,这要求static void Main(string[] args) { string menuCommand = "CertUtilWrapper -hashfile \"%1\""; Register("*", "HashFile", "Create Hash", menuCommand); } 处于系统CertUtilWrapper的某个位置,与PATH本身相同。

还有其他选择。例如,您可以调用CertUtil,批处理文件或PowerShell脚本。

下面是如何使用cmd进行操作。这很简单。请注意,cmd开关是保持窗口打开所必需的。

请注意,这样做的副作用是使/k窗口保持打开状态并显示提示(根据您的受众,这可能会使最终用户感到困惑)。我个人并不喜欢这个缺点。

cmd