How to make compact framework custom controls AutoScale aware

蹲街弑〆低调 提交于 2019-12-05 20:12:32

We generally handle all of the scaling in OnResizein our controls and forms. We also have to support a lot of different devices with crazy dimensions and DPI (some paltforms don't even report the correct DPI!). We found with AutoScaleMode off you can proportionaly use a helper like this to scale a form's children in OnResize. You simply add a Size _initalSize member set to the form size in the constructor. However I've generally found on most forms I have to write custom layout code to appropriate deal with portrait and landscape displays.

        protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);

        // Scale the control
        ScaleChildren(this, ref _initialFormSize);
    }


        public static void ScaleChildren(Control control, ref Size initialSize, float fontFactor)
    {
        if (control == null || control.Size == initialSize)
            return;

        SizeF scaleFactor = new SizeF((float)control.Width / (float)initialSize.Width, (float)control.Height / (float)initialSize.Height);
        initialSize = control.Size;

        if (!float.IsInfinity(scaleFactor.Width) || !float.IsInfinity(scaleFactor.Height))
        {
            foreach (Control child in control.Controls)
            {
                child.Scale(scaleFactor);

                if (child is Panel)
                    continue;

                try
                {
                    // scale the font
                    float scaledFontSize = (float)(int)(child.Font.Size * scaleFactor.Height * fontFactor + 0.5f);

                    System.Diagnostics.Debug.WriteLine(
                        string.Format("ScaleChildren(): scaleFactor = ({0}, {1}); fontFactor = {2}; scaledFontSize = {3}; \"{4}\"",
                        scaleFactor.Width, scaleFactor.Height, fontFactor, scaledFontSize, child.Text));

                    child.Font = new Font(child.Font.Name, scaledFontSize, child.Font.Style);
                }
                catch { }
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!