【问题标题】:WPF Sending chat message which contains a hyperlinkWPF 发送包含超链接的聊天消息
【发布时间】:2025-12-14 18:20:14
【问题描述】:

我有一个小问题,我用c#创建了一个私人聊天消息系统。现在我需要一种向其他人发送可点击链接的方法。

当从列表中选择一个人时,我按下邀请按钮,消息框会出现一条消息,例如“致 User1:从此链接加入”

private void InvBtn_Click(object sender, RoutedEventArgs e)
{
    selectedUser = UsersListBox.SelectedItem.ToString();
    if (selectedUser != login)
    {
        MessageBox.Show("Select other user than yourself");
        return;
    }
    else
    {               
        Msg.Text = selectedUser + " join from this 'link' ";
    }
}

发送后对方得到消息到 RichTextBox 说

来自用户 2:从此链接

加入

不需要打开网站,其他形式会更详细。

【问题讨论】:

  • 您的问题到底是什么?如何在文本运行中嵌入可点击元素?如何在字符串中查找 url?如何打开第二个窗口? “我需要的是一种向其他人发送超链接的方法”相关部分吗?
  • 这个问题设计得有点糟糕。但我需要一种将链接发送给其他人的方法,该链接会打开第二个窗口。超链接不是那么相关。 @ManfredRadlwimmer
  • 嗯,我明白了,但其中哪一部分给您带来了麻烦?你当然不只是停止你的开发,而是决定在 * 上提问。该过程的哪一部分阻碍了您的进步?另外:这个“超链接”可能只是某种实际上不是超链接的标记(如互联网上某些内容的链接),而只是一些特殊格式的文本,对吧? (或者是否有任何与涉及的网络服务器交互?- google.fi 示例并没有真正解释它)
  • 是的,它不需要是网站的超链接。但是,是的,它必须是一种特殊格式的文本,您可以单击它。主要问题是将该“链接”发送给他可以单击的其他人。 @ManfredRadlwimmer
  • 好的,我明白了 - 您是否已经在聊天中使用了某种标记,例如粗体、斜体,还是到目前为止都是纯文本?

标签: c# wpf


【解决方案1】:

您需要创建带有超链接按钮的自定义 MessageBox。

试试这个,这里你需要正确设置 height 和 width 属性......并让构造函数接受参数,以便用户可以按照他们想要的方式设计它。

 public class CustomMessageBox
    {
        public CustomMessageBox()
        {
            Window w = new Window();
            DockPanel panel = new DockPanel();
            TextBlock tx = new TextBlock();
            Paragraph parx = new Paragraph();
            Run run1 = new Run("Text preceeding the hyperlink.");
            Run run2 = new Run("Text following the hyperlink.");
            Run run3 = new Run("Link Text.");
            Hyperlink hyperl = new Hyperlink(run3);
            hyperl.NavigateUri = new Uri("http://search.msn.com");
            tx.Inlines.Add(hyperl);
            panel.Children.Add(tx);
            w.Content = panel;
            w.Show();
        }
    }

来源:https://social.msdn.microsoft.com/Forums/vstudio/en-US/57fcd28b-6e9e-4529-a583-892c8f6d7cc8/hyperlink-in-wpf-message-box?forum=wpf

【讨论】:

    【解决方案2】:

    首先,您需要想出一种方法,将您的特殊标记包含在短信中。您可以将整个消息打包成现有的容器格式(XML、JSON 等),或者为了简单起见,在文本中包含特殊标记,例如:

    Hi User1, join from [This link:12345].
    

    您可以为其他内容添加标记,例如 bold (**bold**)、italics (*italics*) 或网站的实际超链接。

    p>

    另一方面,您将需要一个解析器来检测此特殊标记并将其替换为可点击的链接。在以下示例中,我使用正则表达式来查找和替换格式为 [Text:Command] 的所有文本。

    private IEnumerable<Inline> Parse(string text)
    {
        // Define the format of "special" message segments
        Regex commandFinder = new Regex(@"\[(?<text>.+)\:(?<command>.+)]");
    
        // Find all matches in the message text
        var matches = commandFinder.Matches(text);
    
        // remember where to split the string so we don't lose other 
        // parts of the message
        int previousMatchEnd = 0;
    
        // loop over all matches
        foreach (Match match in matches)
        {
            // extract the text fore it
            string textBeforeMatch = text.Substring(previousMatchEnd, match.Index - previousMatchEnd);
            yield return new Run(textBeforeMatch);
    
            previousMatchEnd = match.Index + match.Length;
    
            // extract information and create a clickable link
            string commandText = match.Groups["text"].Value;
            string command = match.Groups["command"].Value;
    
            // it would be better to use the "Command" property here,
            // but for a quick demo this will do
            Hyperlink link = new Hyperlink(new Run(commandText));
            link.Click += (s, a) => { HandleCommand(command); };
    
            yield return link;
        }
    
        // return the rest of the message (or all of it if there was no match)
        if (previousMatchEnd < text.Length)
            yield return new Run(text.Substring(previousMatchEnd));
    }
    

    在你接收消息的方法中,你可以简单的像这样集成:

    // Where you receive the text
    // This probably is just a `txtOutput.Text += ` until now
    private void OnTextReceived(string text)
    {
        txtOutput.Inlines.AddRange(Parse(text));
    }
    
    // the method that gets invoked when a link is clicked
    // and you can parse/handle the actual command
    private void HandleCommand(string command)
    {
        MessageBox.Show("Command clicked: " + command);
    }
    

    消息Hi User1, join from [this link:1234567890] 将显示为Hi User1, join from this link,并在单击时调用HandleCommand("1234567890")

    【讨论】: