我想在richtextbox中使用文本在记事本中打开一个文本文件

时间:2014-01-31 20:21:02

标签: c# windows winforms

我有一个应用程序,它在组合框中列出了文本文件。用户可以选择文件,然后将字符串添加到列表以在所选文件中搜索这些字符串。使用搜索条件找到的任何行都将复制到richtextbox。我希望能够在RTB中单击的位置单击文本并在记事本中打开所选文件。

2 个答案:

答案 0 :(得分:0)

这样的事情:

void StartInNotepad(string fileName)
{
   Process notepad = new Process();
   notepad.StartInfo.FileName   = "notepad.exe";
   notepad.StartInfo.Arguments = fileName;
   notepad.Start();
}

答案 1 :(得分:0)

您需要知道无法在记事本中打开文件并直接转到特定位置。但你可以在Notepad ++中做到这一点!

首先安装Notepad ++。然后执行以下操作:

  • 为了能够在RTB中单击的位置单击文本并在记事本中打开所选文件,您需要订阅RTB的MouseClick事件。

    private void richTextBoxDialog_MouseClick(object sender, MouseEventArgs e)
    {
        string filePath = comboBoxFiles.SelectedItem.ToString();
    
        if (e.Button == MouseButtons.Left)
        {
            int clickIndex = richTextBoxDialog.GetCharIndexFromPosition(e.Location);
            int index = GetIndexInFile(filePath, richTextBoxDialog.Text, clickIndex);
            Point p = GetPositionFromFileIndex(File.ReadAllText(filePath), index);
            OpenNppXY(filePath, p.X, p.Y);
        }
    }
    
  • 以下方法将返回当前点击位置w.r.t的索引。选定的文件。您可能需要决定考虑哪个:'\ r'和'\ n'作为单个换行符或两个换行符来调整正确的位置。

    int GetIndexInFile(string Filepath, string searchStr, int curIndexRTB)
    {
        string content = File.ReadAllText(Filepath, Encoding.Default);
        return content.IndexOf(searchStr) + curIndexRTB;
    }
    
  • 此方法将返回单击位置的行号和列位置。您可能需要稍微调整一下才能获得正确的位置。

    Point GetPositionFromFileIndex(string input, int index)
    {
        Point p = new Point();
        p.X = input.Take(index).Count(c => c == '\n') + 1;
        p.Y = input.Take(index).ToString().Substring(input.Take(index).ToString().LastIndexOf('\n') + 1).Length + 1;
        return p;
    }
    
  • 最后,这将通过将插入符号放置到所需位置来打开NPP中的选定文件。

    void OpenNppXY(string fileFullPath, int line, int column)
    {
        var nppDir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Notepad++", null, null);
        var nppExePath = Path.Combine(nppDir, "Notepad++.exe");
        var sb = new StringBuilder();
        sb.AppendFormat("\"{0}\" -n{1} -c{2}", fileFullPath, line, column);
        Process.Start(nppExePath, sb.ToString());
    }