www org mapwingis mapwindows mapwindow español c# winforms hyperlink richtextbox rtf

c# - org - mapwindows 5



Enlaces dentro de cuadro de texto rico? (4)

Sé que los richtextboxes pueden detectar enlaces (como http://www.yahoo.com ), pero ¿hay alguna forma de agregar enlaces que parezcan texto pero es un enlace? ¿Como donde puedes elegir la etiqueta del enlace? Por ejemplo, en lugar de aparecer como http://www.yahoo.com , aparece como Haga clic aquí para ir a yahoo

Edición: Olvidé, estoy usando formularios de Windows

edición: ¿hay algo que sea mejor usar (como en el formato más fácil)?


Aquí puede encontrar un ejemplo de cómo agregar un enlace en Textbox enriquecido por linkLabel:

LinkLabel link = new LinkLabel(); link.Text = "something"; link.LinkClicked += new LinkLabelLinkClickedEventHandler(this.link_LinkClicked); LinkLabel.Link data = new LinkLabel.Link(); data.LinkData = @"C:/"; link.Links.Add(data); link.AutoSize = true; link.Location = this.richTextBox1.GetPositionFromCharIndex(this.richTextBox1.TextLength); this.richTextBox1.Controls.Add(link); this.richTextBox1.AppendText(link.Text + " "); this.richTextBox1.SelectionStart = this.richTextBox1.TextLength;

Y aquí está el manejador:

private void link_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start(e.Link.LinkData.ToString()); }


El control RichTextBox estándar (suponiendo que está utilizando Windows Forms) expone un conjunto bastante limitado de características, por lo que desafortunadamente necesitará hacer alguna interoperación de Win32 para lograr eso (en la línea de SendMessage (), CFM_LINK, EM_SETCHARFORMAT, etc.).

Puede encontrar más información sobre cómo hacerlo en esta respuesta aquí en SO.


Encontré una forma que puede no ser la más elegante, pero es solo unas pocas líneas de código y hace el trabajo. Es decir, la idea es simular la apariencia del hipervínculo mediante cambios de fuente y simular el comportamiento del hipervínculo detectando en qué se encuentra el puntero del mouse.

El código:

public partial class Form1 : Form { private Cursor defaultRichTextBoxCursor = Cursors.Default; private const string HOT_TEXT = "click here"; private bool mouseOnHotText = false; // ... Lines skipped (constructor, etc.) private void Form1_Load(object sender, EventArgs e) { // save the right cursor for later this.defaultRichTextBoxCursor = richTextBox1.Cursor; // Output some sample text, some of which contains // the trigger string (HOT_TEXT) richTextBox1.SelectionFont = new Font("Calibri", 11, FontStyle.Underline); richTextBox1.SelectionColor = Color.Blue; // output "click here" with blue underlined font richTextBox1.SelectedText = HOT_TEXT + "/n"; richTextBox1.SelectionFont = new Font("Calibri", 11, FontStyle.Regular); richTextBox1.SelectionColor = Color.Black; richTextBox1.SelectedText = "Some regular text"; } private void richTextBox1_MouseMove(object sender, MouseEventArgs e) { int mousePointerCharIndex = richTextBox1.GetCharIndexFromPosition(e.Location); int mousePointerLine = richTextBox1.GetLineFromCharIndex(mousePointerCharIndex); int firstCharIndexInMousePointerLine = richTextBox1.GetFirstCharIndexFromLine(mousePointerLine); int firstCharIndexInNextLine = richTextBox1.GetFirstCharIndexFromLine(mousePointerLine + 1); if (firstCharIndexInNextLine < 0) { firstCharIndexInNextLine = richTextBox1.Text.Length; } // See where the hyperlink starts, as long as it''s on the same line // over which the mouse is int hotTextStartIndex = richTextBox1.Find( HOT_TEXT, firstCharIndexInMousePointerLine, firstCharIndexInNextLine, RichTextBoxFinds.NoHighlight); if (hotTextStartIndex >= 0 && mousePointerCharIndex >= hotTextStartIndex && mousePointerCharIndex < hotTextStartIndex + HOT_TEXT.Length) { // Simulate hyperlink behavior richTextBox1.Cursor = Cursors.Hand; mouseOnHotText = true; } else { richTextBox1.Cursor = defaultRichTextBoxCursor; mouseOnHotText = false; } toolStripStatusLabel1.Text = mousePointerCharIndex.ToString(); } private void richTextBox1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && mouseOnHotText) { // Insert your own URL here, to navigate to when "hot text" is clicked Process.Start("http://www.google.com"); } } }

Para mejorar el código, se podría crear una forma elegante de asignar múltiples cadenas de "texto activo" a sus propias URL vinculadas (un Dictionary<K, V> tal vez). Una mejora adicional sería la subclase RichTextBox para encapsular la funcionalidad que se encuentra en el código anterior.


Por supuesto, es posible invocar alguna funcionalidad de WIN32 en su control, pero si está buscando formas estándar, revise esta publicación: Crear un hipervínculo en el control TextBox

Hay algunas discusiones sobre diferentes formas de integración.

saludos

Actualización 1: Lo mejor es seguir este método: http://msdn.microsoft.com/en-us/library/f591a55w.aspx

porque los controles del cuadro RichText proporcionan alguna funcionalidad a "DetectUrls". Entonces puedes manejar los enlaces pulsados ​​muy fácilmente:

this.richTextBox1.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.richTextBox1_LinkClicked);

y puede simplemente crear su propio control RichTextBox extendiendo la clase base; allí puede anular los métodos que necesite, por ejemplo, DetectUrls.