我需要使用Paint事件来在运行时定位控件吗?

4

我是一个刚接触C#编程的人,之前从VB6过来的,所以请温柔一点 :P

我一直在使用面板(Panels)来组合控件(例如:面板包含Textbox、Labels、Listview等),然后在运行时使面板自动对齐,以便在不同分辨率下控件能够对齐。但是,我是在面板的绘制例程中进行这个操作的。

例如:

private void pnlTop_Paint(object sender, PaintEventArgs e)
    {
        btnExit.Location                = new Point(this.Width - (this.Left + lblTitleMain.Left + btnExit.Width), 10);
        btnMinimize.Location            = new Point(this.Width - (this.Left + lblTitleMain.Left + (btnExit.Width * 2)), 10);
        btnSettings.Location            = new Point(this.Width - (this.Left + lblTitleMain.Left + (btnExit.Width * 2 + btnExit.Width)), 10);

        lblTitleMain.Left               = (((this.ClientSize.Width - lblTitleMain.Width) / 2) / 2) / 2;
        lblTitleMain.Top                = btnExit.Top + lblTitleMain.Height;

        int intMenuY                    = lblTitleMain.Bottom + 5;
        lnkMenuSystem.Location          = new Point(lblTitleMain.Left + 3, intMenuY);
        lnkMenuDeployment.Location      = new Point(lnkMenuSystem.Right + 50, intMenuY);
        lnkMenuTables.Location          = new Point(lnkMenuDeployment.Right + 50, intMenuY);
        lnkMenuTCP.Location             = new Point(lnkMenuTables.Right + 50, intMenuY);
        lnkMenuDCM.Location             = new Point(lnkMenuTCP.Right + 50, intMenuY);
        lnkMenuProcessData.Location     = new Point(lnkMenuDCM.Right + 50, intMenuY);
        lnkMenuGenerateReports.Location = new Point(lnkMenuProcessData.Right + 50, intMenuY);

        lineMenuButtom.StartPoint       = new Point((((this.ClientSize.Width - lblTitleMain.Width) / 2) / 2) / 2, lnkMenuSystem.Top + lnkMenuSystem.Height + 10);
        lineMenuButtom.EndPoint         = new Point(this.Width - (this.Left + lblTitleMain.Left), lnkMenuSystem.Top + lnkMenuSystem.Height + 10);

        lnkMenuErrorMessage.Location    = new Point(lnkMenuSystem.Left, lineMenuButtom.Y1+5);
        lnkMessageWelcome.Location      = new Point(lineMenuButtom.X2 - lnkMessageWelcome.Width, lineMenuButtom.Y2 + 5);
        GlobalVariables.intGeneralLeft  = lineMenuButtom.StartPoint.X;
        GlobalVariables.intGeneralWidth = lineMenuButtom.X2;
    }

我想问的是:这样做是否正确?原因是我不确定这是否会影响应用程序在旧系统上的性能(假设它将在XP上使用,配置为2G RAM Pentium 4 HT或等效系统)。
1个回答

6
不,那样做肯定是错误的方式。在Paint事件中,频繁触发,你应该尽可能少地在其中工作(而且你绝对不应该修改布局)。相反,你应该在设计时设置Anchor和Dock属性,这样它们就会自动发生。

如果可能的话,同意使用AnchorDock。这些在VB 6中并不存在,但可以让你在WinForms中的生活变得更加轻松。否则,请处理面板控件的Layout事件 - Cody Gray
@CodyGray:更好的选择是:否则,请使用WPF。 - SLaks
@SLaks:非常感谢您的答案和建议。确实在应用程序运行时,当paint方法触发时,我注意到了一个显著的“中断”。非常感谢。然而,就WPF而言,我有点害怕,因为我没有任何经验,并且看起来有点令人生畏。如果没有更多的选择或者我积累更多的经验,我会使用它。 - Sancho Almeda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接