[英]How to set file type association in C#
I have a MDI application. 我有一个MDI应用程序。 This MDI application has lots of other tools including an editor as well.
该MDI应用程序还有许多其他工具,包括编辑器。 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.
我想用我的MDI应用程序的编辑器打开所有“ .txt”文件,从而使我的应用程序成为所有“ .txt”文件的默认查看器。
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 . 每当用户编辑“ .txt”文件时,MDI应用程序应启动,并在编辑器窗口中填充所选“ .txt”文件的内容。
Is there a way I can do that please. 有什么办法可以做的吗?
Thanks 谢谢
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. 但是,请务必弄乱用户的.txt文件关联。 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.
我不知道您的应用程序将部署在哪里,但是如果我从互联网上下载的某个随机实用程序不断更改我的.txt文件关联,我会非常恼火,而且我敢肯定很多其他人也会这样做。
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. 将默认值更改为您的程序,最后以%1作为参数。 Then in your program handle the command line args to do what you want with it.
然后,在程序中处理命令行args,以执行所需的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.