سؤال

هل من الممكن أن شكل بعض النص في WinForm التسمية بدلا من كسر النص إلى عدة تسميات?يرجى تجاهل علامات HTML في تسمية هذا النص ؛ انها تستخدم فقط للحصول على نقطة.

على سبيل المثال:

Dim myLabel As New Label
myLabel.Text = "This is <b>bold</b> text.  This is <i>italicized</i> text."

والتي من شأنها أن تنتج النص في التسمية كما:

هذا هو جريئة النص.هذا هو المائل النص.

هل كانت مفيدة؟

المحلول

هذا غير ممكن مع WinForms التسمية كما هو.التسمية يجب أن يكون بالضبط خط واحد مع واحد بالضبط حجم وجها واحدا.لديك عدة خيارات:

  1. استخدام تسميات منفصلة
  2. إنشاء التحكم الجديدة المشتقة من الفئة التي لا تملك الرسم عبر GDI+ و استخدام هذا بدلا من التسمية;وربما هذا هو الخيار الأفضل ، كما أنه يتيح لك السيطرة الكاملة على كيفية توجيه التحكم في تنسيق النص
  3. استخدام طرف ثالث تحكم التسمية التي سوف تمكنك من إدراج HTML قصاصات (هناك مجموعة الاختيار CodeProject);هذا من شأنه أن يكون شخص آخر تنفيذ #2.

نصائح أخرى

لا حقا, ولكن هل يمكن أنها وهمية مع قراءة فقط RichTextBox بلا حدود.RichTextBox يدعم تنسيق نص منسق (rtf).

الحل آخر, في وقت متأخر إلى الحزب:إذا كنت لا تريد استخدام طرف ثالث مراقبة و أنت تبحث فقط للفت الانتباه إلى بعض النص في التسمية ، و أنت موافق مع تشدد ، يمكنك استخدام LinkLabel.

علما أن الكثيرين يعتبرون هذا 'سهولة الاستخدام الجريمةولكن إذا كنت لا تصميم شيء للمستخدم النهائي الاستهلاك ومن ثم قد يكون شيئا كنت على استعداد أن يكون على ضميرك.

الحيلة هي أن إضافة تعطيل روابط أجزاء من النص الذي تريده وشدد ثم عالميا تعيين الارتباط الألوان لتتناسب مع بقية التسمية.يمكنك تعيين ما يقرب من جميع الخصائص الضرورية في وقت التصميم وبصرف النظر عن 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;

النتيجة:

enter image description here

عملت الحل بالنسبة لي - باستخدام مخصص RichEditBox.مع خصائص سيكون بدت بسيطة التسمية جريئة الدعم.

1) الأولى, إضافة المخصصة الخاصة بك RichTextLabel فئة المعوقين الإقحام :

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) انقسام لك الجملة إلى كلمات مع IsSelected العلم أن تحديد ما إذا كانت هذه الكلمة ينبغي أن تكون جريئة أو لا :

        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) إضافة وظيفة تحويل النص إلى صالح rtf (مع دعم يونيكود!) :

   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();
    }

Sample

تعمل مثل السحر بالنسبة لي!حلول جمعت من :

كيفية تحويل سلسلة إلى RTF في C# ؟

تنسيق النص في مربع نص منسق

كيفية إخفاء الإقحام في RichTextBox?

  1. إنشاء النص ملف RTF في الدفتر
  2. إنشاء الغنية تحكم النص مع عدم وجود حدود للتحرير = false
  3. إضافة ملف RTF إلى المشروع كمورد
  4. في Form1_load لا

    myRtfControl.Rtf = Resource1.MyRtfControlText

AutoRichLabel

      AutoRichLabel with formatted RTF content

لقد تم حل هذه المشكلة من خلال بناء UserControl الذي يحتوي على TransparentRichTextBox هذا هو للقراءة فقط.على TransparentRichTextBox هو RichTextBox التي تسمح أن تكون شفافة:

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;
        }
    }
}

النهائي UserControl بمثابة المجمع من TransparentRichTextBox.للأسف اضطررت إلى حد أن AutoSize على طريقتي الخاصة ، لأن AutoSize من RichTextBox أصبحت مكسورة.

AutoRichLabel.مصمم.cs:

partial class AutoRichLabel
{
    /// <summary> 
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary> 
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Component Designer generated code

    /// <summary> 
    /// Required method for Designer support - do not modify 
    /// the contents of this method with the code editor.
    /// </summary>
    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:

/// <summary>
/// <para>An auto sized label with the ability to display text with formattings by using the Rich Text Format.</para>
/// <para>­</para>
/// <para>Short RTF syntax examples: </para>
/// <para>­</para>
/// <para>Paragraph: </para>
/// <para>{\pard This is a paragraph!\par}</para>
/// <para>­</para>
/// <para>Bold / Italic / Underline: </para>
/// <para>\b bold text\b0</para>
/// <para>\i italic text\i0</para>
/// <para>\ul underline text\ul0</para>
/// <para>­</para>
/// <para>Alternate color using color table: </para>
/// <para>{\colortbl ;\red0\green77\blue187;}{\pard The word \cf1 fish\cf0  is blue.\par</para>
/// <para>­</para>
/// <para>Additional information: </para>
/// <para>Always wrap every text in a paragraph. </para>
/// <para>Different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par)</para>
/// <para>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)</para>
/// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>
/// </summary>
public partial class AutoRichLabel : UserControl
{
    /// <summary>
    /// The rich text content. 
    /// <para>­</para>
    /// <para>Short RTF syntax examples: </para>
    /// <para>­</para>
    /// <para>Paragraph: </para>
    /// <para>{\pard This is a paragraph!\par}</para>
    /// <para>­</para>
    /// <para>Bold / Italic / Underline: </para>
    /// <para>\b bold text\b0</para>
    /// <para>\i italic text\i0</para>
    /// <para>\ul underline text\ul0</para>
    /// <para>­</para>
    /// <para>Alternate color using color table: </para>
    /// <para>{\colortbl ;\red0\green77\blue187;}{\pard The word \cf1 fish\cf0  is blue.\par</para>
    /// <para>­</para>
    /// <para>Additional information: </para>
    /// <para>Always wrap every text in a paragraph. </para>
    /// <para>Different tags can be stacked (i.e. \pard\b\i Bold and Italic\i0\b0\par)</para>
    /// <para>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)</para>
    /// <para>Full specification: http://www.biblioscape.com/rtf15_spec.htm </para>
    /// </summary>
    [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. 
        }
    }

    /// <summary>
    /// Dynamic width of the control. 
    /// </summary>
    [Browsable(false)]
    public new int Width
    {
        get
        {
            return base.Width;
        } 
    }

    /// <summary>
    /// Dynamic height of the control. 
    /// </summary>
    [Browsable(false)]
    public new int Height
    {
        get
        {
            return base.Height;
        }
    }

    /// <summary>
    /// The measured width based on the content. 
    /// </summary>
    public int DesiredWidth { get; private set; }

    /// <summary>
    /// The measured height based on the content. 
    /// </summary>
    public int DesiredHeight { get; private set; }

    /// <summary>
    /// Determines the text will be word wrapped. This is true, when the maximum size has been set. 
    /// </summary>
    public bool WordWrap { get; private set; }

    /// <summary>
    /// Constructor. 
    /// </summary>
    public AutoRichLabel()
    {
        InitializeComponent();
    }

    /// <summary>
    /// Overrides the width and height with the measured width and height
    /// </summary>
    public void Fit()
    {
        base.Width = this.DesiredWidth;
        base.Height = this.DesiredHeight;
    }

    /// <summary>
    /// Will be called when the rich text content of the control changes. 
    /// </summary>
    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. 
    }
}

بناء الجملة من نص منسق تنسيق بسيط جدا:

الفقرة:

{\pard This is a paragraph!\par}

جريئة / مائل / تسطير النص:

\b bold text\b0
\i italic text\i0
\ul underline text\ul0

البديل اللون باستخدام الألوان الجدول:

{\colortbl ;\red0\green77\blue187;}
{\pard The word \cf1 fish\cf0  is blue.\par

ولكن يرجى ملاحظة ما يلي:دائما التفاف كل نص في الفقرة.أيضا, علامات مختلفة يمكن أن تكون مكدسة (أي \pard\b\i Bold and Italic\i0\b0\par) و حرف المسافة خلف الوسم هو تجاهلها.حتى إذا كنت بحاجة إلى مساحة وراء ذلك ، إدراج اثنين المساحات (أي \pard The word \bBOLD\0 is bold.\par).الهروب \ أو { أو }, الرجاء استخدام الرائدة \.لمزيد من المعلومات هناك كامل مواصفات تنسيق نص منسق على الانترنت.

باستخدام هذا بسيط جدا الجملة يمكن ان تنتج شيئا كما ترون في الصورة الأولى.نص منسق المحتوى التي كانت تعلق على 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}

AutoRichLabel with formatted RTF content

إذا كنت ترغب في تمكين التفاف ، يرجى تحديد أقصى عرض إلى الحجم المطلوب.ومع ذلك ، فإن هذا سوف يحل العرض إلى العرض الأقصى ، حتى عندما يكون النص هو أقصر.

وقد متعة!

هناك مقال ممتاز من عام 2009 على قانون مشروع اسمه "محترف HTML العارض سوف تستخدم"الذي ينفذ شيئا من هذا القبيل إلى ما الملصق الأصلي يريد.

أنا استخدامها بنجاح في العديد من المشاريع من الولايات المتحدة.

حل بسيط جدا:

  1. إضافة 2 التسميات على شكل LabelA و LabelB
  2. انتقل إلى خصائص LabelA و ترسو عليه إلى اليسار.
  3. انتقل إلى خصائص LabelB و ترسو عليه إلى اليسار كذلك.
  4. تعيين الخط إلى جريئة من أجل LabelA .

الآن LabelB سيتحول اعتمادا على طول النص من LabelA.

هذا كل شيء.

وأود أن تكون مهتمة أيضا في معرفة ما إذا كان من الممكن.

عندما لم نتمكن من إيجاد حل نحن لجأت إلى عنصر منها SuperLabel التحكم والذي يسمح علامات HTML في التسمية.

تحقيق هذه مسألة قديمة, جوابي هو أكثر لأولئك مثلي ، الذي قد يكون لا يزال يبحث عن مثل هذه الحلول و تتعثر على هذا السؤال.

وبصرف النظر عن ما سبق ذكره ، DevExpress هو LabelControl هو التسمية التي تدعم هذا السلوك - التجريبي هنا.للأسف, هذا هو جزء من رواتبهم المكتبة.

إذا كنت تبحث عن حلول مجانية ، وأعتقد HTML العارض هو أفضل شيء المقبل.

أ FlowLayoutPanel يعمل بشكل جيد بالنسبة للمشكلة الخاصة بك.إذا قمت بإضافة الملصقات إلى تدفق الفريق وشكل كل تسمية الخط و الهامش خصائص, ثم هل يمكن أن يكون مختلف أنماط الخط.سريعة جدا وسهلة الحل للحصول على العمل.

نعم.يمكنك أن تنفذ باستخدام HTML تقديم.من أجل أن ترى ، انقر على الرابط: https://htmlrenderer.codeplex.com/ آمل أن يكون هذا مفيدا.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top