How to associate a program with a file type, but o

2019-01-14 16:47发布

问题:

So, I cannot associate my program with a specific file type without forcing the poor user to enter its admin password (it may be ok for home users, but it is a gigantic problem for users in a corporate env). In this case the only solution is to make the association only for the current user.

I have tried that but something is not working.

If i understand correctly I have to write a key like (let's say) '.mp3' in ctCurUserFileExt and write in it something like 'my_file'. Then in ctCurUserClases I add a key like this:

WriteReg_String(RootKey, ctCurUserClases+ 'my_file\shell\open\command', '', Application.ExeName+ ' "%L"', TRUE) 

However, when I double click the file, Windows asks me with which application should it open it.

Here are the constant:

CONST
     RootKey= 'HKEY_CURRENT_USER';
     ctCurUserFileExt= '\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\';
     ctCurUserClases = '\Software\Classes\';

回答1:

If you want to register the association for every user, write your data to

HKEY_LOCAL_MACHINE\Software\Classes

If you want to register the association for the current user only, write your data to

HKEY_CURRENT_USER\Software\Classes

This is how to do the latter:

with TRegistry.Create do
  try
    RootKey := HKEY_CURRENT_USER;
    if OpenKey('\Software\Classes\.myfile', true) then
      WriteString('', 'MyAppDataFile');
    if OpenKey('\Software\Classes\MyAppDataFile', true) then
      WriteString('', 'My Very Own Text File Type');
    if OpenKey('\Software\Classes\MyAppDataFile\DefaultIcon', true) then
      WriteString('', 'C:\WINDOWS\notepad.exe');
    if OpenKey('\Software\Classes\MyAppDataFile\shell\open\command', true) then
      WriteString('', 'C:\WINDOWS\notepad.exe "%1"');
  finally
    Free;
  end;
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);

This will associate .myfile files, called "My Very Own Text File Type" so that they will have the icon of notepad.exe and will be opened by notepad.exe. The last line tells Explorer to 'reload' itself to reflect the changes made to the file associations. For instance, Explorer file list views will update. The WinAPI function SHChangeNotify is declared in ShlObj.pas, so you need to uses ShlObj.

Notice that the %1 in shell\open\command will expand to the current file. For instance, if you double-click on C:\some dir\test.myfile, then Explorer will execute the command

C:\WINDOWS\notepad.exe "C:\some dir\test.myfile"


回答2:

Have you looked at setting it under HKEY_CURRENT_USER\Software\Classes as per http://support.microsoft.com/kb/257592