C#表单-具有多个文本和图像的按钮 [英] C# Forms - Buttons with multiple texts, and image

查看:118
本文介绍了C#表单-具有多个文本和图像的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建带有两个文本的按钮:左对齐(文本标签本身)和右对齐(热键),以及可能是图像.下面的屏幕截图来自类似的应用程序(不是我的!)

I want to create buttons with two texts: one left (text label itself) and one right (hotkey) aligned, and possibly an image. The screenshot below is from a similar application (not mine!)

支持多行文本会很好,就像图像中的按钮F1-F6一样,但是我可以不用它.我不需要F8按钮的始终处于按下状态".

It would be nice to support multiple lines of text, just like buttons F1-F6 in the image, but I can live without that. I don't need the "always-pressed state" of F8 button.

我正在使用C#和Windows窗体.

I'm using C# and windows forms.

显然,这在WPF中非常简单.在WPF中从未做过任何事情,但是一定会看看.

Apparently this is very simple in WPF. Never did anything in WPF, but will surely take a look.

推荐答案

以下是您可能满意的解决方案:

Here is the solution you may be satisfied with:

public class XButton : Button
{
    public XButton()
    {
        UseVisualStyleBackColor = false;
        TextImageRelation = TextImageRelation.ImageAboveText;
    }
    public override string Text
    {
        get { return ""; }
        set { base.Text = value;}
    }
    public string LeftText { get; set; }
    public string RightText { get; set; }
    protected override void OnPaint(PaintEventArgs pevent)
    {            
        base.OnPaint(pevent);
        Rectangle rect = ClientRectangle;
        rect.Inflate(-5, -5);
        using (StringFormat sf = new StringFormat() { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Far })
        {
            using (Brush brush = new SolidBrush(ForeColor))
            {
                pevent.Graphics.DrawString(LeftText, Font, brush, rect, sf);
                sf.Alignment = StringAlignment.Far;
                pevent.Graphics.DrawString(RightText, Font, brush, rect, sf);
            }
        }
    }
}
//Use it
xButton1.Image = yourImage;
xButton1.LeftText = "How interesting winforms is";
xButton2.RightText = "F12";
//You can add more properties to this XButton class to control how it looks

屏幕截图

这篇关于C#表单-具有多个文本和图像的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆