閱讀200 返回首頁    go iPhone_iPad_Mac_apple


為程序添加係統上下文菜單

using System;
using System.Diagnostics;
using Microsoft.Win32;

namespace SimpleContextMenu
{
    /// <summary>
    /// 在注冊表中注冊和注銷文件上下文菜單.
    /// </summary>
    static class FileShellExtension
    {
        /// <summary>
        /// 注冊上下文菜單
        /// </summary>
        /// <param name="fileType">要注冊的文件類型</param>
        /// <param name="shellKeyName">在注冊表中顯示的名稱</param>
        /// <param name="menuText">在上下文菜單中顯示的文字</param>
        /// <param name="menuCommand">被執行的命令行</param>
        public static void Register(string fileType, string shellKeyName, string menuText, string menuCommand)
        {
            Debug.Assert(!string.IsNullOrEmpty(fileType) &&
                !string.IsNullOrEmpty(shellKeyName) &&
                !string.IsNullOrEmpty(menuText) &&
                !string.IsNullOrEmpty(menuCommand));

            //創建注冊表位置的完整路徑
            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);
            }
        }

        /// <summary>
        /// 注銷上下文菜單.
        /// </summary>
        /// <param name="fileType">注銷的文件類型</param>
        /// <param name="shellKeyName">在注冊表中注冊的名稱</param>
        public static void Unregister(string fileType, string shellKeyName)
        {
            Debug.Assert(!string.IsNullOrEmpty(fileType) && !string.IsNullOrEmpty(shellKeyName));

            // 注冊表中的位置的完整路徑	
            string regPath = string.Format(@"{0}\shell\{1}", fileType, shellKeyName);

            //從注冊表中刪除上下文菜單
            Registry.ClassesRoot.DeleteSubKeyTree(regPath);
        }
    }

}

調用方法:

using System;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

[assembly: CLSCompliant(true)]
namespace SimpleContextMenu
{
    static class Program
    {       
        const string FileType = "Directory";          // 注冊的文件類型
        const string KeyName = "Simple Context Menu"; //在注冊表的上下文菜單名稱
        const string MenuText = "Copy to Grayscale";  // 上下文菜單文本

        [STAThread]
        static void Main(string[] args)
        {
            // 注冊右鍵菜單
            if (!ProcessCommand(args))
            {
                //接收命令行參數處理
            }
        }
	}
}

原文地址:https://www.codeproject.com/Articles/15171/Simple-shell-context-menu


最後更新:2017-04-02 16:47:59

  上一篇:go oracle中的dual詳解
  下一篇:go 讀取Json