Kiq*_*net 3 c# path richtextbox hyperlink winforms
我有VS2010,C#.我在表单中使用RichTextBox.我将DectectUrls属性设置为True.我设置了LinkClicked事件.
我想打开一个这样的文件链接:file:// C:\ Documents and Settings ... 或file:// C:\ Program Files(x86)...
它不适用于带空格的路径.
源代码:
rtbLog.SelectionFont = fnormal;
rtbLog.AppendText("\t. Open Path" + "file://" + PathAbsScript + "\n\n");
// DetectUrls set to true
// launch any http:// or mailto: links clicked in the body of the rich text box
private void rtbLog_LinkClicked(object sender, LinkClickedEventArgs e)
{
try
{
System.Diagnostics.Process.Start(e.LinkText);
}
catch (Exception) {}
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?
小智 5
您可以使用UNICODE非中断空格字符(U + 00A0),而不是使用%20(某些用户可能会发现"难看").例如:
String fileName = "File name with spaces.txt";
FileInfo fi = new FileInfo(fileName);
// Replace any ' ' characters with unicode non-breaking space characters:
richTextBox.AppendText("file://" + fi.FullName.Replace(' ', (char)160));
Run Code Online (Sandbox Code Playgroud)
然后在链接中单击富文本框的处理程序,您将执行以下操作:
private void richTextBox_LinkClicked(object sender, LinkClickedEventArgs e)
{
// Replace any unicode non-break space characters with ' ' characters:
string linkText = e.LinkText.Replace((char)160, ' ');
// For some reason rich text boxes strip off the
// trailing ')' character for URL's which end in a
// ')' character, so if we had a '(' opening bracket
// but no ')' closing bracket, we'll assume there was
// meant to be one at the end and add it back on. This
// problem is commonly encountered with wikipedia links!
if((linkText.IndexOf('(') > -1) && (linkText.IndexOf(')') == -1))
linkText += ")";
System.Diagnostics.Process.Start(linkText);
}
Run Code Online (Sandbox Code Playgroud)