Control alignment switching between LTR and RTL la

2019-01-12 11:54发布

问题:

Although this question is general enough to apply to the web, I'm interested in WinForms in particular.

The application UI switches between LTR and RTL languages without incident. The only obstacle is placement of labels that are associated with input controls such as text boxes.

Left to Right:

Right to Left:

The label placement on the RTL image should also change accordingly.

Is there a generalized, programmatic way to achieve this?

回答1:

Option 1 - Mirror Form (mirrors titlebar too)

If both the RightToLeftLayout and RightToLeft properties are true, mirroring will be turned on for the form, and control placement and text flow will be right-to-left. So set RightToLeftLayout to true and set RightToLeft to yes to have a complete right to left layout.

This way also the form title bar will be mirrored and control box will be shown at left.

Option 2 - Mirror Panel (doesn't mirror title-bar)

If you don't like to have right to left title bar and the control box at left, you should create your right to left container yourself and put controls in it and then set RightToLeftLayout of the container to true and set RightToLeft of the container to yes to have a complete right to left layout in the container without changing the layout of title bar and control box:

using System;
using System.ComponentModel;
using System.Windows.Forms;
public class ExPanel : Panel
{
    const int WS_EX_LAYOUTRTL = 0x400000;
    const int WS_EX_NOINHERITLAYOUT = 0x100000;
    private bool rightToLeftLayout = false;

    [Localizable(true)]
    public bool RightToLeftLayout
    {
        get { return rightToLeftLayout; }
        set
        {
            if (rightToLeftLayout != value)
            {
                rightToLeftLayout = value;
                this.RecreateHandle();
            }
        }
    }
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams CP;
            CP = base.CreateParams;
            if (this.RightToLeftLayout &&
                this.RightToLeft == System.Windows.Forms.RightToLeft.Yes)
                CP.ExStyle = CP.ExStyle | WS_EX_LAYOUTRTL | WS_EX_NOINHERITLAYOUT;
            return CP;
        }
    }
}

Screenshot

Here is a screenshot of Option 1. Look at Close button at left side of title bar:

Here is a screenshot of Option 2. Look at Close button at right side of title bar: