How to set file type association in C#

社会主义新天地 提交于 2021-02-10 19:42:17

问题


I have a MDI application. This MDI application has lots of other tools including an editor as well. I would like to open all the ".txt" files with the editor of my MDI application, thereby making my application as the default viewer of all the ".txt" files.

Whenever the user edits a ".txt" File the MDI application should launch and a editor window should be populated with the contents of the chosen ".txt" file .

Is there a way I can do that please.

Thanks


回答1:


You need to change this reg key:

HKCR\txtfile\shell\open\command

Change the default value to your program with %1 at the end for parameters. Then in your program handle the command line args to do what you want with it.




回答2:


In my application, I do this at launch:

[System.Runtime.InteropServices.DllImport("Shell32.dll")]
private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);

private void GetDefaultsFromRegistry()
{
    if (Registry.GetValue("HKEY_CLASSES_ROOT\\MyApp", String.Empty, String.Empty) == null)
    {
        Registry.SetValue("HKEY_CURRENT_USER\\Software\\Classes\\MyApp", "", "My File Type");
        Registry.SetValue("HKEY_CURRENT_USER\\Software\\Classes\\MyApp", "FriendlyTypeName", "My Friendly Type Name");
        Registry.SetValue("HKEY_CURRENT_USER\\Software\\Classes\\MyApp\\shell\\open\\command", "", 
            "path\\to\\my\\app \"%1\"");
        Registry.SetValue("HKEY_CURRENT_USER\\Software\\Classes\\.ext", "", "MyApp");

        //this call notifies Windows that it needs to redo the file associations and icons
        SHChangeNotify(0x08000000, 0x2000, IntPtr.Zero, IntPtr.Zero);
    }
}

With all paths, names, and extensions changed to your application, of course.

Do be careful with messing with the user's .txt file association, though. I check the assignment on every launch because my application is using a custom type and is only deployed on in-house imaged systems. I don't know where your application is being deployed, but I would be very annoyed if some random utility I downloaded from the internet was constantly changing my .txt file association, and I'm sure a lot of other people would be too.




回答3:


File assocition can programmatically be done like this or it can be done by through registry key like this



来源:https://stackoverflow.com/questions/8882968/how-to-set-file-type-association-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!