Center Dialog on Panel - position is too far right? Why?

  • Thread starter Thread starter Alexander
  • Start date Start date
A

Alexander

Hi, I have a simple Problem. I want to center a dialog on a panel of
an application. I do the following:



public class MyDialog : System.Windows.Forms.Form
{
private Panel m_ParentPanel;

public MyDialog(Panel panel)
{
this.m_ParentPanel = panel;
// some controls
}

protected override void OnLayout(LayoutEventArgs levent)
{
int width = this.m_ParentPanel.ClientRectangle.Width - 40;
if (width > 300) width = 300;
int height = 100;

Point screenLocation =
this.m_ParentPanel.PointToScreen(this.m_ParentPanel.Location);

int x = screenLocation.X +
(this.m_ParentPanel.ClientRectangle.Width-width)/2;
int y = screenLocation.Y +
(this.m_ParentPanel.ClientRectangle.Height-height)/2;

this.Bounds = new Rectangle(x, y, width, height);

base.OnLayout (levent);
}
}



The result is nearly what I want, but the dialog box is always shifted
a bit (20px ?) too far right? What is wrong with this way to center
the dialog box? Or better what is the correct way to do it? ;)

Thanks for any help!
 
Since your MyDialog inherits form Form you should have the property
StartPosition. Set this to "CenterParent".

The application that shows this dialog can pass the Panel has the parent and
everything is done for you. You can then ditch all the OnLayout code.

MyDialog myDialog = new MyDialog();
myDialog.ShowDialog(panel1);

With the StartPosition set to CenterParent the dialog will be centered over
the panel.

HTH
 
Thanks for the quick answer, that would work. But the little program I
am writing is kind of cross platform. It is supposed to work on a PC
and PPC, so I am limited to the functions which are also available for
compact .NET. StartPosition is not part of the compact framework,
thats why I have to use the workaround.
I corrected the position by substraction 10 from the x und y
coordinated and it looks OK, but I am still interrested why the
position is not centered.
 
Back
Top