C# 在组合框中对齐文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11817062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:23:20  来源:igfitidea点击:

Align Text in Combobox

c#winformscomboboxvisual-c#-express-2010

提问by user1366440

I want to align my text in combo box so that it will show in the center of combobox tell me how to do this also you can see there is a default border around a combo box when it is in focus how can i remove that border also Kindly solve my two problems Thanks

我想在组合框中对齐我的文本,以便它显示在组合框的中心告诉我如何执行此操作,您还可以看到组合框周围有一个默认边框,当它处于焦点时如何我也可以删除该边框请解决我的两个问题 谢谢

采纳答案by Hans Passant

This isn't supported for ComboBox. The exact reasons are lost in the fog of time, ComboBox has been around since the early nineties, but surely has something to do with the awkwardness of getting the text in the textbox portion to line up with the text in the dropdown. Custom drawing with DrawItem cannot solve it either, that only affects the appearance of the dropdown items.

ComboBox 不支持此功能。确切的原因在时间的迷雾中迷失了,ComboBox 自 90 年代初就已经存在,但肯定与让文本框部分中的文本与下拉列表中的文本对齐的尴尬有关。使用 DrawItem 自定义绘图也无法解决它,只会影响下拉项的外观。

As a possible workaround, you could perhaps do something outlandish like padding the item strings with spaces so they lookcentered. You'll need TextRenderer.MeasureText() to figure out how many spaces to add for each item.

作为一种可能的解决方法,您也许可以做一些奇怪的事情,例如用空格填充项目字符串,使它们看起来居中。您将需要 TextRenderer.MeasureText() 来确定要为每个项目添加多少个空格。

The "border" you are talking about is not a border, it is the focus rectangle. You can't get rid of that either, Windows refuses to let you create a UI that won't show the control with the focus. Users that prefer the keyboard over the mouse care about that. No workaround for that one.

您所说的“边框”不是边框,而是焦点矩形。您也无法摆脱它,Windows 拒绝让您创建一个不会显示带有焦点的控件的 UI。喜欢键盘而不是鼠标的用户关心这一点。没有解决方法。

回答by Levi Botelho

Winforms is fairly unflexible when it comes to the customisation of controls. If you are looking for a more customised user experience then I recommend that you look into creating a WPF application which allows you to define custom controls. It will take some work though, so it's only something that you will want to undertake if you really find it to be necessary. Here is a decent site to get you started http://www.wpftutorial.net/

Winforms 在自定义控件方面相当不灵活。如果您正在寻找更自定义的用户体验,那么我建议您考虑创建一个 WPF 应用程序,它允许您定义自定义控件。不过,这需要一些工作,因此只有在您确实认为有必要时才愿意进行。这是一个不错的网站,可以帮助您入门http://www.wpftutorial.net/

回答by Matt Fritz

Set RightToLeftproperty to true.
It does NOT reverse the sequence of characters. It only right-justifies.

RightToLeft属性设置为true.
它不会反转字符序列。它只是正确证明。

回答by Martin Braun

This article will help you: http://blog.michaelgillson.org/2010/05/18/left-right-center-where-do-you-align/

这篇文章将帮助你:http: //blog.michaelgillson.org/2010/05/18/left-right-center-where-do-you-align/

The trick is to set the DrawMode-Property of the ComboBox to OwnerDrawFixedas well as subscribe to its event DrawItem.

诀窍是DrawMode将 ComboBox的-Property设置OwnerDrawFixed为以及订阅其 event DrawItem

Your event should contain the following code:

您的事件应包含以下代码:

// Allow Combo Box to center aligned
private void cbxDesign_DrawItem(object sender, DrawItemEventArgs e)
{
  // By using Sender, one method could handle multiple ComboBoxes
  ComboBox cbx = sender as ComboBox;
  if (cbx != null)
  {
    // Always draw the background
    e.DrawBackground();

    // Drawing one of the items?
    if (e.Index >= 0)
    {
      // Set the string alignment.  Choices are Center, Near and Far
      StringFormat sf = new StringFormat();
      sf.LineAlignment = StringAlignment.Center;
      sf.Alignment = StringAlignment.Center;

      // Set the Brush to ComboBox ForeColor to maintain any ComboBox color settings
      // Assumes Brush is solid
      Brush brush = new SolidBrush(cbx.ForeColor);

      // If drawing highlighted selection, change brush
      if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        brush = SystemBrushes.HighlightText;

      // Draw the string
      e.Graphics.DrawString(cbx.Items[e.Index].ToString(), cbx.Font, brush, e.Bounds, sf);
    }
  }
}

ComboBox-Preview

组合框-预览

To right align the items you can simply replace StringAlignment.Centerwith StringAlignment.Far.

要正确对齐您可以简单地替换StringAlignment.Center为的项目StringAlignment.Far

回答by A.elm5zngy

you can do something like this by adding space before Display member in your Query

您可以通过在查询中的显示成员之前添加空格来执行类似的操作

for example :

例如 :

combobox1.DataSource = Query(Select col1 , ('   '+col2) as Col2 from tableName) 
combobox1.DisplayMember = "Col2";
combobox1.ValueMember = "col1";

回答by Reza Aghaei

The post is a bit old but it may be still worth to say:

帖子有点旧,但可能仍然值得说:

both requirements are possible for Windows Forms ComboBox:

Windows Forms ComboBox 可以满足这两个要求:

  • Text align center (text area and the dropdown)
    • For the text area, find the Editcontrol and set the ES_CENTERstyle for the control.
    • For the dropdown items or the selected item in drop-down mode, to align text to center, just make the control owner-drawn and draw the text at center.
  • Get rid of focus rectangle
    • Make the control owner-drawn and just don't draw focus rectangle.
  • 文本居中对齐(文本区域和下拉菜单)
    • 对于文本区域,找到Edit控件并设置控件的ES_CENTER样式。
    • 对于下拉项或下拉模式中的选定项,要使文本居中对齐,只需使控件自绘并在中心绘制文本即可。
  • 摆脱焦点矩形
    • 使控件所有者绘制,只是不绘制焦点矩形。

Example

例子

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
public class MyComboBox : ComboBox
{
    public MyComboBox()
    {
        DrawMode = DrawMode.OwnerDrawFixed;
    }

    [DllImport("user32.dll")]
    static extern int GetWindowLong(IntPtr hWnd, int nIndex);
    [DllImport("user32.dll")]
    static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
    const int GWL_STYLE = -16;
    const int ES_LEFT = 0x0000;
    const int ES_CENTER = 0x0001;
    const int ES_RIGHT = 0x0002;
    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
        public int Width { get { return Right - Left; } }
        public int Height { get { return Bottom - Top; } }
    }
    [DllImport("user32.dll")]
    public static extern bool GetComboBoxInfo(IntPtr hWnd, ref COMBOBOXINFO pcbi);

    [StructLayout(LayoutKind.Sequential)]
    public struct COMBOBOXINFO
    {
        public int cbSize;
        public RECT rcItem;
        public RECT rcButton;
        public int stateButton;
        public IntPtr hwndCombo;
        public IntPtr hwndEdit;
        public IntPtr hwndList;
    }
    protected override void OnHandleCreated(EventArgs e)
    {
        base.OnHandleCreated(e);
        SetupEdit();
    }
    private int buttonWidth = SystemInformation.HorizontalScrollBarArrowWidth;
    private void SetupEdit()
    {
        var info = new COMBOBOXINFO();
        info.cbSize = Marshal.SizeOf(info);
        GetComboBoxInfo(this.Handle, ref info);
        var style = GetWindowLong(info.hwndEdit, GWL_STYLE);
        style |= 1;
        SetWindowLong(info.hwndEdit, GWL_STYLE, style);
    }
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        base.OnDrawItem(e);
        e.DrawBackground();
        var txt = "";
        if (e.Index >= 0)
            txt = GetItemText(Items[e.Index]);
        TextRenderer.DrawText(e.Graphics, txt, Font, e.Bounds,
            ForeColor, TextFormatFlags.Left | TextFormatFlags.HorizontalCenter);
    }
}