Проект типа Class Library состоит из 4 файлов
| Код | // ******************************************************************************* // Title: BatchResults.cs // Description: Sample shell extension // *******************************************************************************
using System; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32; using System.Windows.Forms; using System.Diagnostics;
namespace ShellExt { [Guid("6B3A1F0C-C382-40d6-AA13-33B0AB46EEAA")] public class BatchResultContextMenu: IShellExtInit, IContextMenu { #region Protected Members protected const string guid = "{6B3A1F0C-C382-40d6-AA13-33B0AB46EEAA}"; protected string m_fileName;// файл, по которому щёлкнули protected string apStPath;// путь к нашей программе protected uint m_hDrop = 0; #endregion
#region IContextMenu // IContextMenu int IContextMenu.QueryContextMenu(uint hMenu, uint iMenu, int idCmdFirst, int idCmdLast, uint uFlags) { // Create the popup to insert uint hmnuPopup = Helpers.CreatePopupMenu();
int id = 1; if ( (uFlags & 0xf) == 0 || (uFlags & (uint)CMF.CMF_EXPLORE) != 0) { uint nselected = Helpers.DragQueryFile(m_hDrop, 0xffffffff, null, 0); if (nselected == 1) { StringBuilder sb = new StringBuilder(1024); Helpers.DragQueryFile(m_hDrop, 0, sb, sb.Capacity + 1); m_fileName = sb.ToString();
// Populate the popup menu with file-specific items id = PopulateMenu(hmnuPopup, idCmdFirst+ id); } //if (nselected == 2)// 2 уровень вложенности //{ // StringBuilder sb = new StringBuilder(1024); // Helpers.DragQueryFile(m_hDrop, 0, sb, sb.Capacity + 1); // m_fileName = sb.ToString();
// // Populate the popup menu with file-specific items // id = PopulateMenu(hmnuPopup, idCmdFirst + id); //} // Добавление выпадающего меню в контекстное(Add the popup to the context menu) MENUITEMINFO mii = new MENUITEMINFO(); mii.cbSize = 48; mii.fMask = (uint) MIIM.TYPE | (uint)MIIM.STATE | (uint) MIIM.SUBMENU; mii.hSubMenu = (int) hmnuPopup; mii.fType = (uint) MF.STRING; mii.dwTypeData = "Это мой пункт"; mii.fState = (uint) MF.ENABLED; Helpers.InsertMenuItem(hMenu, (uint)iMenu, 1, ref mii);
// Добавляем разделитель(Add a separator) MENUITEMINFO sep = new MENUITEMINFO(); sep.cbSize = 48; sep.fMask = (uint )MIIM.TYPE; sep.fType = (uint) MF.SEPARATOR; Helpers.InsertMenuItem(hMenu, iMenu+1, 1, ref sep); } return id; }
void AddMenuItem(uint hMenu, string text, int id, uint position) { MENUITEMINFO mii = new MENUITEMINFO(); mii.cbSize = 48; mii.fMask = (uint)MIIM.ID | (uint)MIIM.TYPE | (uint)MIIM.STATE; mii.wID = id; mii.fType = (uint)MF.STRING; mii.dwTypeData = text; mii.fState = (uint)MF.ENABLED; Helpers.InsertMenuItem(hMenu, position, 1, ref mii); }
int PopulateMenu(uint hMenu, int id) { // Захватываем информацию о файле(Grab some info about the file) bool done = ProcessBatchResults();
if (done) { //AddMenuItem(hMenu, "Reschedule", id, 0); //AddMenuItem(hMenu, "Retry Now", ++id, 1); //AddMenuItem(hMenu, "Cancel", ++id, 2); AddMenuItem(hMenu, "Зашифровать", id, 0); AddMenuItem(hMenu, "Расшифровать", ++id, 1); AddMenuItem(hMenu, "Подписать", ++id, 2); } else { // Uses 100-baed values to distinguish on the "done" status AddMenuItem(hMenu, "Commit", 100 + id, 0); AddMenuItem(hMenu, "Rollback", 100 + (++id), 1); }
return id++; } bool ProcessBatchResults() { FileInfo fi = new FileInfo(m_fileName); return (fi.Length >0); }
void IContextMenu.GetCommandString(int idCmd, uint uFlags, int pwReserved, StringBuilder commandString, int cchMax) { switch(uFlags) { case (uint)GCS.VERB: commandString = new StringBuilder("..."); break; case (uint)GCS.HELPTEXT: commandString = new StringBuilder("..."); break; } }
void IContextMenu.InvokeCommand (IntPtr pici) { try {// здесь указываем на выполнение наших команд Type typINVOKECOMMANDINFO = Type.GetType("ShellExt.INVOKECOMMANDINFO"); INVOKECOMMANDINFO ici = (INVOKECOMMANDINFO)Marshal.PtrToStructure(pici, typINVOKECOMMANDINFO); switch (ici.verb-1) { case 0: Encrypt(); break; case 1: Decrypt(); break; case 2: RetryNowJob(); break; case 100: CommitJob(); break; case 101: RollbackJob(); break; } } catch(Exception) { } } #endregion
#region IShellExtInit int IShellExtInit.Initialize (IntPtr pidlFolder, IntPtr lpdobj, uint hKeyProgID) { try { if (lpdobj != (IntPtr)0) { // Get info about the directory IDataObject dataObject = (IDataObject)Marshal.GetObjectForIUnknown(lpdobj); FORMATETC fmt = new FORMATETC(); fmt.cfFormat = CLIPFORMAT.CF_HDROP; fmt.ptd = 0; fmt.dwAspect = DVASPECT.DVASPECT_CONTENT; fmt.lindex = -1; fmt.tymed = TYMED.TYMED_HGLOBAL; STGMEDIUM medium = new STGMEDIUM(); dataObject.GetData(ref fmt, ref medium); m_hDrop = medium.hGlobal; } } catch(Exception) { } return 0; }
#endregion #region Private Members // команда зашифровать->Личный ключ->EFS, временно просто зашифровать private void Encrypt() { // здесь указываем, какое действие будет происходить try { Process process = new Process(); // шифруем выбранный файл process.StartInfo.CreateNoWindow = false; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; string ap = @"C:\Windows\system32\cipher.exe ",//Path. + "\\Utils\\cipher.exe", paramz = " /e /a " + Path.GetFileName(m_fileName); process.StartInfo.Arguments = paramz; // тут строка типа winrar.exe -ed -f process.StartInfo.FileName = ap; process.Start(); process.WaitForExit();
MessageBox.Show("Файл \"" + m_fileName/*Path.GetFileName(m_fileName)*/ + "\" зашифрован успешно!", "FrontLine", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception exc) { MessageBox.Show("Ошибка во время шифрования папки!\n" + exc.Message, "FrontLine", MessageBoxButtons.OK, MessageBoxIcon.Error); } //MessageBox.Show("Gotta cancel the job", Path.GetFileName(m_fileName)); } // команда Расшифровать private void Decrypt() { Process process = new Process(); // шифруем выбранный файл process.StartInfo.CreateNoWindow = false; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; string ap = @"C:\Windows\system32\cipher.exe ",//Path. + "\\Utils\\cipher.exe", paramz = " /d /a " + Path.GetFileName(m_fileName); process.StartInfo.Arguments = paramz; // тут строка типа winrar.exe -ed -f process.StartInfo.FileName = ap; process.Start(); process.WaitForExit(); MessageBox.Show("Файл \"" + Path.GetFileName(m_fileName) + "\" расшифрован успешно!", "FrontLine", MessageBoxButtons.OK, MessageBoxIcon.Information); //MessageBox.Show("Gotta reschedule the job", Path.GetFileName(m_fileName)); } private void RetryNowJob() { MessageBox.Show("Gotta retry the job NOW", Path.GetFileName(m_fileName)); } private void CommitJob() { MessageBox.Show("Gotta commit the job", Path.GetFileName(m_fileName)); } private void RollbackJob() { MessageBox.Show("Gotta rollback the job", Path.GetFileName(m_fileName)); } #endregion
#region Registration [System.Runtime.InteropServices.ComRegisterFunctionAttribute()] static void DLLRegisterServer(String str1) { try { // For Winnt set me as an approved shellex RegistryKey root; RegistryKey rk; root = Registry.LocalMachine; rk = root.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved", true); //rk.SetValue(guid.ToString(), "BatchResults shell extension"); rk.SetValue(guid.ToString(), "MyContextMenu extension"); rk.Close();
// Set "Folder\\shellex\\ContextMenuHandlers\\BatchResults" regkey to my guid root = Registry.ClassesRoot; //rk = root.CreateSubKey("BatchResultsFile\\shellex\\ContextMenuHandlers\\BatchResults"); rk = root.CreateSubKey("*\\shellex\\ContextMenuHandlers\\MyContextMenu");// новое rk = root.OpenSubKey("*\\shellex\\ContextMenuHandlers\\MyContextMenu",true);// новое rk.SetValue("", guid.ToString()); rk.Close(); } catch(Exception e) { System.Console.WriteLine(e.ToString()); } }
[System.Runtime.InteropServices.ComUnregisterFunctionAttribute()] static void DllUnregisterServer(String str1) { try { RegistryKey root; RegistryKey rk;
// Remove ShellExtenstions registration root = Registry.LocalMachine; rk = root.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Shell Extensions\\Approved", true); rk.DeleteValue(guid); rk.Close();
// Delete regkey root = Registry.ClassesRoot; //root.DeleteSubKey("BatchResultsFile\\shellex\\ContextMenuHandlers\\BatchResults"); root.DeleteSubKey("*\\ShellEx\\ContextMenuHandlers\\SimpleShlExt"); } catch(Exception e) { System.Console.WriteLine(e.ToString()); } } #endregion
} }
|
[code=csharp]
Добавлено через 4 минуты и 10 секунд Осталное в прикреплённом файле
Добавлено через 4 минуты и 41 секунду Основная работа в файлике batchresults. Для чего нужен Commands не понятно. Мне необходимо увеличить вложенность контекстного меню. Там, где расшифровать-> ещё пункт, а ещё 1. Типа структуры п.0 0.1 0.1.1 0.1.1.1 0.1.1.2 0.2 0.3 На форме моего основонго приложения(они не связаны) 2 кнопки: загрузить контекстное меню выгрузить контекстное меню
|