C# 我想使用richtextbox中的文本在记事本中打开一个文本文件
我有一个在组合框中列出文本文件的应用程序。用户可以选择一个文件,然后将字符串添加到列表中,以在所选文件中搜索这些字符串。使用搜索条件找到的任何行都会复制到richtextbox。我希望能够单击文本并在记事本中RTB中单击的位置打开所选文件。类似以下内容:C# 我想使用richtextbox中的文本在记事本中打开一个文本文件,c#,windows,winforms,C#,Windows,Winforms,我有一个在组合框中列出文本文件的应用程序。用户可以选择一个文件,然后将字符串添加到列表中,以在所选文件中搜索这些字符串。使用搜索条件找到的任何行都会复制到richtextbox。我希望能够单击文本并在记事本中RTB中单击的位置打开所选文件。类似以下内容: void StartInNotepad(string fileName) { Process notepad = new Process(); notepad.StartInfo.FileName = "notepad.exe"
void StartInNotepad(string fileName)
{
Process notepad = new Process();
notepad.StartInfo.FileName = "notepad.exe";
notepad.StartInfo.Arguments = fileName;
notepad.Start();
}
您需要知道,您无法在记事本中打开文件并直接转到特定位置。但是你可以用记事本++来做 首先安装记事本++。然后执行以下操作: 要能够单击文本并在记事本中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;
}
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());
}
最后,将插入符号放置到所需位置,从而在NPP中打开所选文件
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;
}
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());
}
这个类似问题的答案解释了如何使用Notepad++进行同样的操作。我在这个答案中看到的唯一问题是如何在richtextbox中选择文本,并将其用作移动光标的点。