不同分辨率下的 Windows 窗体大小问题

Asa*_*lik 2 c# winforms

我是窗口窗体开发的新手,在开发了一些窗体后,我注意到窗体在不同分辨率下无法正确显示,窗体在某些分辨率下超出了屏幕

我想知道是否有任何设置可以根据分辨率自动调整表单,或者是否有任何技巧或某些技术可以用来设计表单。

请详细说明您的答案,因为我对 Windows 窗体开发非常熟悉。

谢谢

Moh*_*lim 5

您可以在加载事件中循环表单上的每个控件,并重新缩放它们和表单本身,比例是您设计表单的屏幕尺寸与应用程序屏幕尺寸之间的比率正在工作。

    //this is a utility static class
    public static class Utility{


    public static void fitFormToScreen(Form form, int h, int w)
    {

        //scale the form to the current screen resolution
        form.Height = (int)((float)form.Height * ((float)Screen.PrimaryScreen.Bounds.Size.Height / (float)h));
        form.Width = (int)((float)form.Width * ((float)Screen.PrimaryScreen.Bounds.Size.Width / (float)w));

        //here font is scaled like width
            form.Font = new Font(form.Font.FontFamily, form.Font.Size * ((float)Screen.PrimaryScreen.Bounds.Size.Width / (float)w));

        foreach (Control item in form.Controls)
        {
            fitControlsToScreen(item, h, w);
        }

    }

    static void fitControlsToScreen(Control cntrl, int h, int w)
    {
        if (Screen.PrimaryScreen.Bounds.Size.Height != h)
        {

            cntrl.Height = (int)((float)cntrl.Height * ((float)Screen.PrimaryScreen.Bounds.Size.Height / (float)h));
            cntrl.Top = (int)((float)cntrl.Top * ((float)Screen.PrimaryScreen.Bounds.Size.Height / (float)h));

        }
        if (Screen.PrimaryScreen.Bounds.Size.Width != w)
        {

            cntrl.Width = (int)((float)cntrl.Width * ((float)Screen.PrimaryScreen.Bounds.Size.Width / (float)w));
            cntrl.Left = (int)((float)cntrl.Left * ((float)Screen.PrimaryScreen.Bounds.Size.Width / (float)w));

                cntrl.Font = new Font(cntrl.Font.FontFamily, cntrl.Font.Size * ((float)Screen.PrimaryScreen.Bounds.Size.Width / (float)w));

        }

        foreach (Control item in cntrl.Controls)
        {
            fitControlsToScreen(item, h, w);
        }
    }
    }


        //inside form load event
        //send the width and height of the screen you designed the form for
        Utility.fitFormToScreen(this, 788, 1280);
        this.CenterToScreen();
Run Code Online (Sandbox Code Playgroud)