'C# 폼위치를 마음대로'에 해당되는 글 1건

728x90

C# 에서 자식폼을 띄울 때 MainForm 의 위치가 변경되도 항상 MainForm 위에 뜨도록 하는 방법을 알아봤다.


자식폼의 위치를 고려하지 않고 폼을 띄우는 방법은

Form2 frm2 = new Form2();

frm2.Show();

라고 하면 된다.


메인폼(MainForm) 의 위치가 변경되더라도 자식폼이 메인폼의 위에 뜨게 하고  싶었다.

메인폼을 종료하고 나서 다음에 실행할 때 메인폼의 시작위치를 마지막 종료시점의 위치를 기억하게 하는 방법은

http://link2me.tistory.com/863 게시글에 설명되어 있다.


자식폼을 띄울 때 메인폼 위에 위치하도록 하는 방법은

Point parentPoint = this.Location;
Form2 frm2 = new Form2();
frm2.StartPosition = FormStartPosition.Manual;  // 폼의 위치가 Location 의 속성에 의해서 결정
frm2.Location = new Point(parentPoint.X + 100, parentPoint.Y + 100);
frm2.Show();


메인폼의 위치, 높이, 너비를 가지고 자식폼을 띄울때 같이 반영해주면 된다.

Point parentPoint = this.Location; // 메인폼(현재폼)의 위치
int parentHeight = this.Height; // 메인폼
(현재폼)의 높이
int parentWidth = this.Width; // 메인폼
(현재폼)의 너비


자식폼의 위치를 메인폼의 우측에 위치하게 하고 싶다고 하면

frm2.Location = new Point(parentPoint.X + int parentWidth, parentPoint.Y);

로 해주면 된다.


화면사이즈까지 고려해서 화면내에서 보이게 하려고 하면 모니터 사이즈를 알아내야 한다.

int screenWidth = Screen.PrimaryScreen.WorkingArea.Width;

int screenHeight = Screen.PrimaryScreen.WorkingArea.Height;
MessageBox.Show(screenWidth.ToString() + " X " + screenHeight.ToString());

내 모니터의 크기를 알아보니 1920 X 1040 으로 나온다.


int screenWidth = Screen.PrimaryScreen.Bounds.Width; //모니터 스크린 가로크기
int screenHeight = Screen.PrimaryScreen.Bounds.Height; //모니터 스크린 세로크기
이걸로 확인해보면 1920 X 1080 으로 나온다.

WorkingArea 와 Bounds 차이다.


가 차치하는 공간은 작업공간이 아니라고 계산을 한 것이다.


듀얼모니터의 가로크기와 세로크기는

int screenWidth = System.Windows.Forms.SystemInformation.VirtualScreen.Width; //듀얼 모니터 가로 크기
int screenHeight = System.Windows.Forms.SystemInformation.VirtualScreen.Height; //듀얼 모니터 세로 크기
로 알아낼 수 있다.


모니터 크기를 알아냈다면, 이제 자식폼의 높이와 너비도 알아내야 한다.

int childWidth = frm2.Width;
int childHeight = frm2.Height;


이제 parantPoint.X + parentWidth + childWidth > screenHeight 가 넘어가는 조건이 발생할 때에는 X좌표의 값을 어떻게 주겠다. 마찬가지로 Y좌표에 대해서도 어떻게 주겠다고 계산을 해서 if else 조건문을 적어서 표시되도록 하면 된다.


** https://msdn.microsoft.com/ko-kr/library/system.windows.forms.formstartposition(v=vs.110).aspx

FormStartPosition 설명이 나와있다.

구글링해서 찾은 자료도 적어놓는다. 아래 두 코드는 서로 내용이 동일하다.

Form2 frm2 = new Form2();
frm2.StartPosition = FormStartPosition.CenterParent;
frm2.Show(this);

Form2 frm2 = new Form2();
frm2.StartPosition = FormStartPosition.Manual;
frm2.Location = new Point(this.ClientSize.Width / 2, this.ClientSize.Height / 2);
frm2.Show();

블로그 이미지

Link2Me

,