1

I have developed a Text Editor in WinForms. you can download it from here and use it. It works fine. But when I right-click a text file in Windows Explorer and try to open it, it doesn't show it. I have searched solution for this on Web, but failed. Can you suggest a resolution to this. Or should I use RichTextBox. I also tried to create a simple Test project with RichTextBox and used LoadFile().

// Load the contents of the file into the RichTextBox.
richTextBox1.LoadFile(openFile1.FileName, RichTextBoxStreamType.RichText);

This caused a file format error.

4

3 回答 3

1

好的,根据您的评论和提供的代码,它不会从 Windows 打开文件。

当 windows 将文件发送给程序以打开它时,它将作为第一个参数发送给 exe,例如notepad.exe C:\Users\Sean\Desktop\FileToOpen.txt.

您需要使用Environment.CommandLineor来获取参数Environment.GetCommandLineArgs()

有关详细信息,请参见此处:如何将命令行参数传递给 WinForms 应用程序?

我会在你的表单Load事件中处理这个并将参数传递给你的函数:

string filename = Environment.GetCommandLineArgs()[0];
richTextBox1.LoadFile(filename, RichTextBoxStreamType.RichText);
于 2012-11-14T14:00:16.377 回答
1

I just solved the problem. Thanks for your help.
I am adding answer for future help who face the similar problem.
Here is the solution:

Call the following method from Form_Load():

public void LoadFileFromExplorer()
{
   string[] args = Environment.GetCommandLineArgs();

   if (args.Length > 1)
   {
     string filename1 = Environment.GetCommandLineArgs()[1];
     richTextBox1.LoadFile(filename1, RichTextBoxStreamType.PlainText);
   }
}

To make this work, change Main():

static void Main(String[] args)
    {
        if (args.Length > 0)
        {
            // run as windows app
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
        else
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
于 2012-11-14T14:46:41.157 回答
1

问题是使用:

richTextBox1.LoadFile(openFile1.FileName, RichTextBoxStreamType.RichText);

您必须选择富文本格式 (RTF)文件,这是因为加载普通文本文件会给您带来文件格式错误 (ArgumentException)。所以你可以用这种方式加载它:

string[] lines = System.IO.File.ReadAllLines(openFile1.FileName);
richTextBox1.Lines = lines;
于 2012-11-14T11:59:30.327 回答