Форматирование текста в WinForm Label
Можно ли отформатировать определенный текст 9X_labels в метке WinForm вместо того, чтобы разбивать 9X_windows-forms-app текст на несколько меток? Не обращайте внимания 9X_labels на теги HTML в тексте метки; это используется 9X_labels только для того, чтобы получить мою точку 9X_text зрения.
Например:
Dim myLabel As New Label myLabel.Text = "This is bold text. This is italicized text."
В результате текст на этикетке 9X_window-forms будет выглядеть так:
Это полужирный текст. Это курсив текст.
Ответ #1
Ответ на вопрос: Форматирование текста в WinForm Label
Это невозможно с меткой WinForms как таковой. На 9X_window-forms этикетке должен быть ровно один шрифт, ровно 9X_winform один размер и одно начертание. У вас есть 9X_windows-forms несколько вариантов:
- Используйте отдельные этикетки
- Создайте новый класс, производный от Control, который сам рисует через GDI+, и используйте его вместо Label; это, вероятно, ваш лучший вариант, так как он дает вам полный контроль над тем, как указать элементу управления форматировать его текст
- Используйте сторонний элемент управления ярлыками, который позволит вам вставлять фрагменты HTML (их много — проверьте CodeProject); это будет чья-то реализация #2.
Ответ #2
Ответ на вопрос: Форматирование текста в WinForm Label
Не совсем, но вы можете сымитировать это 9X_windows-forms с помощью RichTextBox только для чтения 9X_winform без границ. RichTextBox поддерживает формат 9X_label Rich Text Format (rtf).
Ответ #3
Ответ на вопрос: Форматирование текста в WinForm Label
Другой обходной путь, поздно для стороны: если 9X_windows-form вы не хотите использовать сторонний элемент 9X_formatting управления, и вы просто хотите привлечь 9X_formatting внимание к некоторому тексту в вашем ярлыке, и вас 9X_labels устраивает подчеркивание, вы можете использовать 9X_formating LinkLabel.
Обратите внимание, что многие считают это 9X_winforms «usability crime», но если вы не разрабатываете что-то 9X_window-form для конечного пользователя, возможно, вы 9X_formatting готовы оставить это на своей совести.
Хитрость 9X_windows-form заключается в том, чтобы добавить отключенные 9X_formatting ссылки к тем частям текста, которые вы хотите 9X_window-forms подчеркнуть, а затем глобально установить 9X_winforms цвета ссылок в соответствии с остальной 9X_label частью метки. Вы можете установить почти 9X_labels все необходимые свойства во время разработки, кроме 9X_text части Links.Add()
, но здесь они находятся в коде:
linkLabel1.Text = "You are accessing a government system, and all activity " + "will be logged. If you do not wish to continue, log out now."; linkLabel1.AutoSize = false; linkLabel1.Size = new Size(365, 50); linkLabel1.TextAlign = ContentAlignment.MiddleCenter; linkLabel1.Links.Clear(); linkLabel1.Links.Add(20, 17).Enabled = false; // "government system" linkLabel1.Links.Add(105, 11).Enabled = false; // "log out now" linkLabel1.LinkColor = linkLabel1.ForeColor; linkLabel1.DisabledLinkColor = linkLabel1.ForeColor;
Результат:
- О, замечательно. Я никогда не знал, что метки ссылок могут иметь определенные области в качестве ссылок. На самом деле это намного ближе к вариан ...
Ответ #4
Ответ на вопрос: Форматирование текста в WinForm Label
Для меня сработало решение - использование 9X_formating настраиваемого RichEditBox. При правильных 9X_window-form свойствах он будет выглядеть как простая 9X_windows-forms-app этикетка с полужирным шрифтом.
1) Сначала добавьте 9X_window-forms свой собственный класс RichTextLabel с отключенным 9X_windows-forms-app курсором:
public class RichTextLabel : RichTextBox { public RichTextLabel() { base.ReadOnly = true; base.BorderStyle = BorderStyle.None; base.TabStop = false; base.SetStyle(ControlStyles.Selectable, false); base.SetStyle(ControlStyles.UserMouse, true); base.SetStyle(ControlStyles.SupportsTransparentBackColor, true); base.MouseEnter += delegate(object sender, EventArgs e) { this.Cursor = Cursors.Default; }; } protected override void WndProc(ref Message m) { if (m.Msg == 0x204) return; // WM_RBUTTONDOWN if (m.Msg == 0x205) return; // WM_RBUTTONUP base.WndProc(ref m); } }
2) Разделите предложение на слова 9X_text с флагом IsSelected, который определяет, должно 9X_plaintext ли это слово быть жирным или нет:
private void AutocompleteItemControl_Load(object sender, EventArgs e) { RichTextLabel rtl = new RichTextLabel(); rtl.Font = new Font("MS Reference Sans Serif", 15.57F); StringBuilder sb = new StringBuilder(); sb.Append(@"{\rtf1\ansi "); foreach (var wordPart in wordParts) { if (wordPart.IsSelected) { sb.Append(@"\b "); } sb.Append(ConvertString2RTF(wordPart.WordPart)); if (wordPart.IsSelected) { sb.Append(@"\b0 "); } } sb.Append(@"}"); rtl.Rtf = sb.ToString(); rtl.Width = this.Width; this.Controls.Add(rtl); }
3) Добавьте 9X_winform функцию для преобразования текста в действительный 9X_labels формат RTF (с поддержкой Unicode!):
private string ConvertString2RTF(string input) { //first take care of special RTF chars StringBuilder backslashed = new StringBuilder(input); backslashed.Replace(@"\", @"\\"); backslashed.Replace(@"{", @"\{"); backslashed.Replace(@"}", @"\}"); //then convert the string char by char StringBuilder sb = new StringBuilder(); foreach (char character in backslashed.ToString()) { if (character <= 0x7f) sb.Append(character); else sb.Append("\\u" + Convert.ToUInt32(character) + "?"); } return sb.ToString(); }
Для меня 9X_windows.forms действует как оберег! Решения составлены 9X_windows-forms из:
How to convert a string to RTF in C#?
How to hide the caret in a RichTextBox?
Ответ #5
Ответ на вопрос: Форматирование текста в WinForm Label
- Создайте текст как файл RTF в Wordpad
- Создать элемент управления форматированным текстом без границ и editable = false
- Добавьте файл RTF в проект в качестве ресурса
-
В Form1_load сделать
myRtfControl.Rtf = Resource1.MyRtfControlText
9X_winforms
Ответ #6
Ответ на вопрос: Форматирование текста в WinForm Label
AutoRichLabel
Я решил эту проблему, создав UserControl
, который содержит 9X_plaintext TransparentRichTextBox
, доступный только для чтения. TransparentRichTextBox
- это RichTextBox
, который 9X_formating позволяет быть прозрачным:
TransparentRichTextBox.cs:
public class TransparentRichTextBox : RichTextBox { [DllImport("kernel32.dll", CharSet = CharSet.Auto)] static extern IntPtr LoadLibrary(string lpFileName); protected override CreateParams CreateParams { get { CreateParams prams = base.CreateParams; if (TransparentRichTextBox.LoadLibrary("msftedit.dll") != IntPtr.Zero) { prams.ExStyle |= 0x020; // transparent prams.ClassName = "RICHEDIT50W"; } return prams; } } }
Последний 9X_text UserControl
действует как оболочка для TransparentRichTextBox
. К сожалению, мне 9X_winform пришлось ограничить его до AutoSize
по-своему, потому 9X_windows-forms-app что AutoSize
в RichTextBox
стал сломанным.
AutoRichLabel.designer.cs:
partial class AutoRichLabel { ///
/// Required designer variable. ///
private System.ComponentModel.IContainer components = null; ///
/// Clean up any resources being used. ///
/// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code ///
/// Required method for Designer support - do not modify /// the contents of this method with the code editor. ///
private void InitializeComponent() { this.rtb = new TransparentRichTextBox(); this.SuspendLayout(); // // rtb // this.rtb.BorderStyle = System.Windows.Forms.BorderStyle.None; this.rtb.Dock = System.Windows.Forms.DockStyle.Fill; this.rtb.Location = new System.Drawing.Point(0, 0); this.rtb.Margin = new System.Windows.Forms.Padding(0); this.rtb.Name = "rtb"; this.rtb.ReadOnly = true; this.rtb.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None; this.rtb.Size = new System.Drawing.Size(46, 30); this.rtb.TabIndex = 0; this.rtb.Text = ""; this.rtb.WordWrap = false; this.rtb.ContentsResized += new System.Windows.Forms.ContentsResizedEventHandler(this.rtb_ContentsResized); // // AutoRichLabel // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.BackColor = System.Drawing.Color.Transparent; this.Controls.Add(this.rtb); this.Name = "AutoRichLabel"; this.Size = new System.Drawing.Size(46, 30); this.ResumeLayout(false); } #endregion private TransparentRichTextBox rtb; }
AutoRichLabel.cs:
///
/// An auto sized label with the ability to display text with formattings by using the Rich Text Format. /// /// Short RTF syntax examples: /// /// Paragraph: /// {\pard This is a paragraph!\par} /// /// Bold / Italic / Underline: /// \b bold text\b0 /// \i italic text\i0 /// \ul underline text\ul0 /// /// Alternate color using color table: /// {\colortbl ;\red0\green77\blue187;}{\pard The word \cf1 fish\cf0 is blue.\par /// /// Additional information: /// Always wrap every text in a paragraph. /// Different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par) /// The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \pard The word \bBOLD\0 is bold.\par) /// Full specification: http://www.biblioscape.com/rtf15_spec.htm ///
public partial class AutoRichLabel : UserControl { ///
/// The rich text content. /// /// Short RTF syntax examples: /// /// Paragraph: /// {\pard This is a paragraph!\par} /// /// Bold / Italic / Underline: /// \b bold text\b0 /// \i italic text\i0 /// \ul underline text\ul0 /// /// Alternate color using color table: /// {\colortbl ;\red0\green77\blue187;}{\pard The word \cf1 fish\cf0 is blue.\par /// /// Additional information: /// Always wrap every text in a paragraph. /// Different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par) /// The space behind a tag is ignored. So if you need a space behind it, insert two spaces (i.e. \pard The word \bBOLD\0 is bold.\par) /// Full specification: http://www.biblioscape.com/rtf15_spec.htm ///
[Browsable(true)] public string RtfContent { get { return this.rtb.Rtf; } set { this.rtb.WordWrap = false; // to prevent any display bugs, word wrap must be off while changing the rich text content. this.rtb.Rtf = value.StartsWith(@"{\rtf1") ? value : @"{\rtf1" + value + "}"; // Setting the rich text content will trigger the ContentsResized event. this.Fit(); // Override width and height. this.rtb.WordWrap = this.WordWrap; // Set the word wrap back. } } ///
/// Dynamic width of the control. ///
[Browsable(false)] public new int Width { get { return base.Width; } } ///
/// Dynamic height of the control. ///
[Browsable(false)] public new int Height { get { return base.Height; } } ///
/// The measured width based on the content. ///
public int DesiredWidth { get; private set; } ///
/// The measured height based on the content. ///
public int DesiredHeight { get; private set; } ///
/// Determines the text will be word wrapped. This is true, when the maximum size has been set. ///
public bool WordWrap { get; private set; } ///
/// Constructor. ///
public AutoRichLabel() { InitializeComponent(); } ///
/// Overrides the width and height with the measured width and height ///
public void Fit() { base.Width = this.DesiredWidth; base.Height = this.DesiredHeight; } ///
/// Will be called when the rich text content of the control changes. ///
private void rtb_ContentsResized(object sender, ContentsResizedEventArgs e) { this.AutoSize = false; // Disable auto size, else it will break everything this.WordWrap = this.MaximumSize.Width > 0; // Enable word wrap when the maximum width has been set. this.DesiredWidth = this.rtb.WordWrap ? this.MaximumSize.Width : e.NewRectangle.Width; // Measure width. this.DesiredHeight = this.MaximumSize.Height > 0 && this.MaximumSize.Height < e.NewRectangle.Height ? this.MaximumSize.Height : e.NewRectangle.Height; // Measure height. this.Fit(); // Override width and height. } }
Синтаксис 9X_windows-forms расширенного текстового формата довольно 9X_formating прост:
Абзац:
{\pard This is a paragraph!\par}
Полужирный / курсив / подчеркнутый 9X_windows-forms-app текст:
\b bold text\b0 \i italic text\i0 \ul underline text\ul0
Альтернативный цвет с помощью таблицы 9X_winform цветов:
{\colortbl ;\red0\green77\blue187;} {\pard The word \cf1 fish\cf0 is blue.\par
Но учтите: всегда помещайте каждый 9X_winform текст в абзац. Кроме того, можно складывать 9X_label разные теги (например, \pard\b\i Bold and Italic\i0\b0\par
), а символ пробела 9X_winform за тегом игнорируется. Поэтому, если вам 9X_winforms нужен пробел, вставьте два пробела (например, \pard The word \bBOLD\0 is bold.\par
). Чтобы 9X_formating избежать \
, {
или }
, используйте начальный 9X_window-forms \
. Для получения дополнительной информации 9X_text существует full specification of the rich text format online.
Используя этот довольно простой 9X_window-form синтаксис, вы можете создать что-то вроде 9X_windows-forms того, что вы видите на первом изображении. Содержимое 9X_label форматированного текста, которое было прикреплено 9X_labels к свойству RtfContent
моего AutoRichLabel
в первом изображении, было:
{\colortbl ;\red0\green77\blue187;} {\pard\b BOLD\b0 \i ITALIC\i0 \ul UNDERLINE\ul0 \\\{\}\par} {\pard\cf1\b BOLD\b0 \i ITALIC\i0 \ul UNDERLINE\ul0\cf0 \\\{\}\par}
Если 9X_plaintext вы хотите включить перенос слов, установите 9X_window-forms желаемый размер для максимальной ширины. Однако 9X_winform это зафиксирует максимальную ширину, даже 9X_windows-form если текст короче.
Удачи!
Ответ #7
Ответ на вопрос: Форматирование текста в WinForm Label
Есть отличная статья 2009 года в Code Project 9X_labels под названием "A Professional HTML Renderer You Will Use", которая реализует 9X_labels нечто подобное тому, что хочет исходный 9X_formating плакат.
Я успешно использую его в нескольких 9X_labels наших проектах.
Ответ #8
Ответ на вопрос: Форматирование текста в WinForm Label
Очень простое решение:
- Добавьте в форму 2 метки: LabelA и LabelB.
- Перейдите к свойствам LabelA и закрепите его слева.
- Перейдите к свойствам LabelB и также закрепите его слева.
- Установите для шрифта LabelA полужирный шрифт.
Теперь LabelB будет 9X_windows.forms сдвигаться в зависимости от длины текста 9X_windows-forms LabelA.
Вот и все.
Ответ #9
Ответ на вопрос: Форматирование текста в WinForm Label
Мне тоже было бы интересно узнать, возможно 9X_label ли это.
Когда мы не смогли найти решение, мы 9X_formatting прибегли к элементу управления Component 9X_winforms Ones «SuperLabel», который позволяет использовать 9X_label HTML-разметку в этикетке.
Ответ #10
Ответ на вопрос: Форматирование текста в WinForm Label
Понимая, что это старый вопрос, мой ответ 9X_windows-form больше предназначен для тех, кто, как и 9X_labels я, все еще может искать такие решения и 9X_winform наткнуться на этот вопрос.
Помимо того, что 9X_text уже упоминалось, DevExpress LabelControl - это метка, которая 9X_formatting поддерживает такое поведение - demo here. Увы, это 9X_label часть платной библиотеки.
Если вы ищете бесплатные 9X_formatting решения, я считаю, что HTML Renderer - лучший вариант.
Ответ #11
Ответ на вопрос: Форматирование текста в WinForm Label
FlowLayoutPanel хорошо подойдет для вашей 9X_labels проблемы. Если вы добавите метки на панель 9X_window-forms потока и отформатируете свойства шрифта 9X_windows-forms и поля каждой метки, тогда у вас могут быть 9X_windows-forms-app разные стили шрифтов. Довольно быстрое и 9X_window-form простое решение для начала работы.
-
6
-
29
-
3
-
2
-
1
-
1
-
5
-
4
-
2
-
10
-
7
-
7
-
3
-
6
-
3
-
5
-
6
-
4
-
2
-
6
-
3
-
6
-
3
-
6
-
4
-
1
-
5
-
5
-
5
-
18
-
17
-
4
-
5
-
4
-
2
-
2
-
6
-
8
-
6
-
16
-
5
-
6
-
1
-
4
-
9
-
4
-
8
-
4
-
7
-
1