copy_hook.py
2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# A sample shell copy hook.
# To demostrate:
# * Execute this script to register the context menu.
# * Open Windows Explorer
# * Attempt to move or copy a directory.
# * Note our hook's dialog is displayed.
import sys, os
import pythoncom
from win32com.shell import shell, shellcon
import win32gui
import win32con
import winerror
# Our shell extension.
class ShellExtension:
_reg_progid_ = "Python.ShellExtension.CopyHook"
_reg_desc_ = "Python Sample Shell Extension (copy hook)"
_reg_clsid_ = "{1845b6ba-2bbd-4197-b930-46d8651497c1}"
_com_interfaces_ = [shell.IID_ICopyHook]
_public_methods_ = ["CopyCallBack"]
def CopyCallBack(self, hwnd, func, flags,
srcName, srcAttr, destName, destAttr):
# This function should return:
# IDYES Allows the operation.
# IDNO Prevents the operation on this folder but continues with any other operations that have been approved (for example, a batch copy operation).
# IDCANCEL Prevents the current operation and cancels any pending operations.
print "CopyCallBack", hwnd, func, flags, srcName, srcAttr, destName, destAttr
return win32gui.MessageBox(hwnd, "Allow operation?", "CopyHook",
win32con.MB_YESNO)
def DllRegisterServer():
import _winreg
key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,
"directory\\shellex\\CopyHookHandlers\\" +
ShellExtension._reg_desc_)
_winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_)
key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,
"*\\shellex\\CopyHookHandlers\\" +
ShellExtension._reg_desc_)
_winreg.SetValueEx(key, None, 0, _winreg.REG_SZ, ShellExtension._reg_clsid_)
print ShellExtension._reg_desc_, "registration complete."
def DllUnregisterServer():
import _winreg
try:
key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,
"directory\\shellex\\CopyHookHandlers\\" +
ShellExtension._reg_desc_)
except WindowsError, details:
import errno
if details.errno != errno.ENOENT:
raise
try:
key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,
"*\\shellex\\CopyHookHandlers\\" +
ShellExtension._reg_desc_)
except WindowsError, details:
import errno
if details.errno != errno.ENOENT:
raise
print ShellExtension._reg_desc_, "unregistration complete."
if __name__=='__main__':
from win32com.server import register
register.UseCommandLine(ShellExtension,
finalize_register = DllRegisterServer,
finalize_unregister = DllUnregisterServer)
#!/usr/bin/env python