WPF 기반 RichTextBox 에 텍스트를 입력 할때 텍스트 내용을 추출하여 HyperLink를 만들어 줍니다.
참고한 사이트 소스가 잘 동작 하지 않아 조금 수정하였습니다.
찾느라 시간좀 걸렸네요.
XAML 에서 RichTextBox 속성
IsReadOnly="True" IsDocumentEnabled="True"
.cs 소스 코드
private static readonly Regex regexUrl = new Regex(@"(?#Protocol)(?:(?:ht|f)tp(?:s?)\:\/\/|~/|/)?(?#Username:Password)(?:\w+:\w+@)?(?#Subdomains)(?:(?:[-\w]+\.)+(?#TopLevel Domains)(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?#Port)(?::[\d]{1,5})?(?#Directories)(?:(?:(?:/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|/)+|\?|#)?(?#Query)(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?#Anchor)(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?");
private static readonly Regex regexSmilies = new Regex(@"(:\)(?!\)))");
CreateHyperLink(string text)
{
foreach (Match match in regexUrl.Matches(text))
{
TextPointer p1 = ToTextPointer(match.Index);
TextPointer p2 = ToTextPointer(match.Index + match.Length);
if (p1 == null || p2 == null)
{
}
else
{
Hyperlink hlink = new Hyperlink(p1, p2);
hlink.Click += OnUrlClick;
hlink.NavigateUri = new Uri(match.ToString());
}
}
}
private TextPointer ToTextPointer(int index)
{
int count = 0;
TextPointer position = txtTitle.Document.ContentStart.GetNextContextPosition(LogicalDirection.Forward).GetNextContextPosition(LogicalDirection.Forward);
while (position != null)
{
if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
{
string textRun = position.GetTextInRun(LogicalDirection.Forward);
int length = textRun.Length;
if (count + length > index)
{
return position.GetPositionAtOffset(index - count);
}
count += length;
}
position = position.GetNextContextPosition(LogicalDirection.Forward);
}
return null;
}
private static void OnUrlClick(object sender, RoutedEventArgs e)
{
Process.Start((sender as Hyperlink).NavigateUri.AbsoluteUri);
}
참고한 글은 다음 링크에
http://hintdesk.com/c-insert-images-and-hyperlinks-into-richtextbox-in-wpf/
당신의 의견을 작성해 주세요.