c# 윈도우폼 열려있는 폼 중에서 원하는 폼 찾기
Form fc = Application.OpenForms["폼이름"];
Form fc = Application.OpenForms["폼이름"];
출처 : http://stackoverflow.com/questions/2576156/winforms-how-can-i-make-messagebox-appear-centered-on-mainform
// 클래스에 사용되는 네임스페이스들
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
//1단계 - 파일에 아래와 같이 클래스를 추가한다 - 시작
class CenterWinDialog : IDisposable {
private int mTries = 0;
private Form mOwner;
public CenterWinDialog(Form owner) {
mOwner = owner;
owner.BeginInvoke(new MethodInvoker(findDialog));
}
private void findDialog() {
// Enumerate windows to find the message box
if (mTries < 0) return;
EnumThreadWndProc callback = new EnumThreadWndProc(checkWindow);
if (EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero)) {
if (++mTries < 10) mOwner.BeginInvoke(new MethodInvoker(findDialog));
}
}
private bool checkWindow(IntPtr hWnd, IntPtr lp) {
// Checks if <hWnd> is a dialog
StringBuilder sb = new StringBuilder(260);
GetClassName(hWnd, sb, sb.Capacity);
if (sb.ToString() != "#32770") return true;
// Got it
Rectangle frmRect = new Rectangle(mOwner.Location, mOwner.Size);
RECT dlgRect;
GetWindowRect(hWnd, out dlgRect);
MoveWindow(hWnd,
frmRect.Left + (frmRect.Width - dlgRect.Right + dlgRect.Left) / 2,
frmRect.Top + (frmRect.Height - dlgRect.Bottom + dlgRect.Top) / 2,
dlgRect.Right - dlgRect.Left,
dlgRect.Bottom - dlgRect.Top, true);
return false;
}
public void Dispose() {
mTries = -1;
}
// P/Invoke declarations
private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lp);
[DllImport("user32.dll")]
private static extern bool EnumThreadWindows(int tid, EnumThreadWndProc callback, IntPtr lp);
[DllImport("kernel32.dll")]
private static extern int GetCurrentThreadId();
[DllImport("user32.dll")]
private static extern int GetClassName(IntPtr hWnd, StringBuilder buffer, int buflen);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT rc);
[DllImport("user32.dll")]
private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int w, int h, bool repaint);
private struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
}
//1단계 - 파일에 아래와 같이 클래스를 추가한다 - 끝
// 테스트 메시지 박스를 쓰는 방법
// this 가 부모 form 임
private void button1_Click(object sender, EventArgs e) {
using (new CenterWinDialog(this)) {
MessageBox.Show("Nobugz waz here");
}
}
// fmain -> 부모 Form
// 부모 Form의 좌표, 크기를 계산
int mainformx = fmain.Location.X;
int mainformy = fmain.Location.Y;
int mainformwidth = fmain.Size.Width;
int mainformheight = fmain.Size.Height;
// fchild -> 자식 Form
// 자식 Form의 크기를 계산
form fchild = new form();
int childformwidth = fchild.Size.Width;
int childformheight = fchild.Size.Height;
// 자식 Form 보이기
fchild.Show();
// 자식 Form의 위치 수정
fchild.Location = new Point(mainformx + (mainformwidth / 2) - (childformwidth / 2), mainformy + (mainformheight / 2) - (childformheight / 2));