First you need to come up with a way to include your special markup in the text message. You can either pack the entire message in an existing container format (XML, JSON, etc.) or to keep things simple include special markers within the text, for example:
Hi User1, join from [This link:12345].
The same way you could include markup for other things like bold (**bold**
), italics (*italics*
), or actual hyperlinks to websites.
On the other side, you will need a parser that detects this special markup and replaces it with a clickable link. In the following example I'm using Regex to find and replace all text in the format [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));
}
In the method where you receive the message, you can simply integrate it like this:
// 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);
}
The message Hi User1, join from [this link:1234567890]
will show up as Hi User1, join from this link
and will invoke HandleCommand("1234567890")
when clicked.
