Search code examples
c++visual-studiomfcvisual-studio-2017registry

MFC SetRegistryKey opposite function? What am I missing?


In my app the default Registry key is created called:

SetRegistryKey(_T("Trains"));

It places that "root" key value like so:

Computer\HKEY_CURRENT_USER\SOFTWARE\Trains

My app saves all the window info and other data in subkeys under Trains. I have a "reset" menu item that when the user activates, I would like to delete that "root" key and all the subkeys under it.

If I'm in registry editor, it is simply a right click and delete....and blamo, all gone.

I've read other threads here and on Google and there seems to be multiple ways to do this.... I've tried DelRegTree with little success and I'm unclear why this process is so cumbersome to do with multiple functions and recursion to find all the keys, delete them, then remove the root key.

https://learn.microsoft.com/en-us/cpp/mfc/reference/cwinapp-class?view=msvc-160#delregtree

I've tried DelRegTree(\\HKEY_CURRENT_USER\\SOFTWARE, _T("Trains")); but that doesn't work. How should I approach this seemingly easy task?


Solution

  • You can use the SHDeleteKey() function. You can use HKEY_CURRENT_USER for the first argument and specify the key path (from that) in the second:

    #include <shlwapi.h>
    LSTATUS status = SHDeleteKey(HKEY_CURRENT_USER, _T("SOFTWARE\\Trains"));
    

    You will need to include "Shwlapi.lib" in your link.

    (Note: Calling the DelRegTree member of CWinApp may also work, if you use the same arguments; but you can't add the \\SOFTWARE part to the first argument – that will have to be included in the key path/name.)