If you ever wanted to delete some registry key including all its subkeys you probably have seen this

Windows 95: The RegDeleteKey function deletes a key and all its descendents.

Windows NT: The RegDeleteKey function deletes the specified key. This function cannot delete a key that has subkeys.


So I wanted to create compatabile proc for both NT and 9x and here is what I came up for:



DelRegKeyEx proc _hKey:dword,pszKey:dword
LOCAL hKey:dword
LOCAL LastWriteTime:SYSTEMTIME
LOCAL szKeyName[MAX_PATH]:byte
LOCAL dwName:dword
LOCAL dwCounter:dword
;int 3
PrintStringByAddr pszKey
; try deleting first, maybe it doesnt have subkeys
invoke RegDeleteKey,_hKey,pszKey
.if eax!=ERROR_SUCCESS
invoke RegOpenKeyEx,_hKey,pszKey,0,\
KEY_ALL_ACCESS,addr hKey
.if eax==ERROR_SUCCESS
mov dwCounter,0
.while 1
mov dwName,MAX_PATH
invoke memfill,addr szKeyName,MAX_PATH,0
invoke RegEnumKeyEx,hKey,dwCounter,addr szKeyName,\
addr dwName,0,0,0,0;addr LastWriteTime
.if eax==ERROR_SUCCESS
INVOKE DelRegKeyEx,hKey,addr szKeyName
.else
; no more keys under this key
.break
.endif
inc dwCounter
.endw
invoke RegCloseKey,hKey
.endif
.endif

ret
DelRegKeyEx endp


But this doesnt work as it should, it only deletes some keys and some doesn't. Looks like RegEnumKeyEx fails and doesnt always enumerate all keys. Does anyone have idea what could be the problem?
Posted on 2004-03-26 20:33:02 by Mikky
You can use the SHDeleteKey function in shlwapi.dll
Posted on 2004-03-27 02:49:58 by TQN
Mikky, have you checked the error value, and seen if it's a trivial thing like not having the necessary permissions to enum/delete on NT?
Posted on 2004-03-27 02:57:53 by f0dder
SHDeleteKey will not delete subkeys on nt, here is quote from MSDN

Windows NT: The specified key must not contain any subkeys.


Ok I've found the error,




DelRegKeyEx proc _hKey:dword,pszKey:dword
LOCAL hKey:dword
LOCAL LastWriteTime:SYSTEMTIME
LOCAL szKeyName[MAX_PATH]:byte
LOCAL dwName:dword
LOCAL dwCounter:dword
;int 3
PrintStringByAddr pszKey
; try deleting first, maybe it doesnt have subkeys
invoke RegDeleteKey,_hKey,pszKey
.if eax!=ERROR_SUCCESS
invoke RegOpenKeyEx,_hKey,pszKey,0,\
KEY_ALL_ACCESS,addr hKey
.if eax==ERROR_SUCCESS
mov dwCounter,0
.while 1
mov dwName,MAX_PATH
invoke memfill,addr szKeyName,MAX_PATH,0
invoke RegEnumKeyEx,hKey,dwCounter,addr szKeyName,\
addr dwName,0,0,0,0;addr LastWriteTime
.if eax==ERROR_SUCCESS
INVOKE DelRegKeyEx,hKey,addr szKeyName
[COLOR=red]dec dwCounter[/COLOR]
.else
; no more keys under this key
.break
.endif
inc dwCounter
.endw
invoke RegCloseKey,hKey
.endif
.endif

ret
DelRegKeyEx endp


When you delete some key, RegEnumKeyEx will got messed up because it tracks subkeys with counter.
Here I just decrement counter after key deleting and it works ok now (assuming that you will always have priviledges to delete key). Moderators can move this to algo section, it can be useful to someone.
Posted on 2004-03-27 09:01:55 by Mikky