C #에서 창을 가운데에 맞추려면 어떻게합니까?
현재 창을 가운데에 맞추는 방법이 필요합니다. 예를 들어 사용자가 버튼을 누르면 창을 화면 중앙에 놓기를 원합니다. startposition 속성을 사용할 수 있다는 것을 알고 있지만 응용 프로그램을 처음 시작할 때 이외의 다른 방법을 사용할 수는 없습니다. 그러면 양식을 화면 중앙에 어떻게 배치합니까?
Form.CenterToScreen () 메서드를 사용하십시오 .
은 Using 속성 창을
양식 선택 → 속성 창으로 이동 → "시작 위치"선택 → 원하는 곳을 선택하십시오.
프로그래밍 방식으로
Form form1 = new Form(); form1.StartPosition = FormStartPosition.CenterScreen; form1.ShowDialog();
참고 : 코드에서 Form.CenterToScreen ()을 직접 호출하지 마십시오. 여기를 읽으 십시오 .
한 줄 :
this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
(Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);
Windows Forms에서 :
this.StartPosition = FormStartPosition.CenterScreen;
WPF에서 :
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
그게 당신이해야 할 전부입니다 ...
런타임 중에 창을 가운데에 맞추려면 아래 코드를 사용하여 응용 프로그램에 복사하십시오.
protected void ReallyCenterToScreen()
{
Screen screen = Screen.FromControl(this);
Rectangle workingArea = screen.WorkingArea;
this.Location = new Point() {
X = Math.Max(workingArea.X, workingArea.X + (workingArea.Width - this.Width) / 2),
Y = Math.Max(workingArea.Y, workingArea.Y + (workingArea.Height - this.Height) / 2)};
}
마지막으로 위의 메소드를 호출하여 작동시킵니다.
ReallyCenterToScreen();
런타임에서 양식 중심 맞추기
1. 양식의 다음 속성을 설정하십시오
.-> StartPosition : CenterScreen-
> WindowState : Normal
런타임에 양식을 중앙에 배치하지만 양식 크기가 예상보다 크면 두 번째 단계를 수행하십시오.
2. InitializeComponent () 뒤에 사용자 정의 크기를 추가하십시오.
public Form1()
{
InitializeComponent();
this.Size = new Size(800, 600);
}
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace centrewindow
{
public partial class Form1 : Form
{
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
[DllImport("user32.dll")]
public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(HandleRef hwnd, out RECT lpRect);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CentreWindow(Handle, GetMonitorDimensions());
}
private void CentreWindow(IntPtr handle, Size monitorDimensions)
{
RECT rect;
GetWindowRect(new HandleRef(this, handle), out rect);
var x1Pos = monitorDimensions.Width/2 - (rect.Right - rect.Left)/2;
var x2Pos = rect.Right - rect.Left;
var y1Pos = monitorDimensions.Height/2 - (rect.Bottom - rect.Top)/2;
var y2Pos = rect.Bottom - rect.Top;
SetWindowPos(handle, 0, x1Pos, y1Pos, x2Pos, y2Pos, 0);
}
private Size GetMonitorDimensions()
{
return SystemInformation.PrimaryMonitorSize;
}
}
}
핸들을 얻을 수있는 모든 창 중앙
이것을 사용하십시오 :
this.CenterToScreen(); // This will take care of the current form
폼의 위치 속성을 사용하십시오. 원하는 왼쪽 상단 지점으로 설정
원하는 x = (데스크톱 너비-form_witdh) / 2
원하는 y = (데스크탑 높이-출발 높이) / 2
You can use the Screen.PrimaryScreen.Bounds
to retrieve the size of the primary monitor (or inspect the Screen
object to retrieve all monitors). Use those with MyForms.Bounds
to figure out where to place your form.
Might not be completely relevant to the question. But maybe can help someone.
Center Screen non of the above work for me. Reason was I was adding controls dynamically to the form. Technically when it centered it was correct , based on the form before adding the controls.
So here was my solution. ( Should work with both scenarios )
int x = Screen.PrimaryScreen.Bounds.Width - this.PreferredSize.Width;
int y = Screen.PrimaryScreen.Bounds.Height - this.PreferredSize.Height;
this.Location = new Point(x / 2, y / 2);
So you will notice that I am using "PreferredSize" instead of just using Height / Width. The preferred size will hold the value of the form after adding the controls. Where Height / Width won't.
Hope this helps someone .
Cheers
다중 모니터의 경우 올바른 모니터 / 화면을 중앙에 배치하려면 다음 라인을 시도하십시오.
// Save values for future(for example, to center a form on next launch)
int screen_x = Screen.FromControl(Form).WorkingArea.X;
int screen_y = Screen.FromControl(Form).WorkingArea.Y;
// Move it and center using correct screen/monitor
Form.Left = screen_x;
Form.Top = screen_y;
Form.Left += (Screen.FromControl(Form).WorkingArea.Width - Form.Width) / 2;
Form.Top += (Screen.FromControl(Form).WorkingArea.Height - Form.Height) / 2;
참고 URL : https://stackoverflow.com/questions/4601827/how-do-i-center-a-window-onscreen-in-c
'development' 카테고리의 다른 글
직렬 대기열에서 dispatch_async와 dispatch_sync의 차이점은 무엇입니까? (0) | 2020.07.15 |
---|---|
CSS 오버플로-한 줄의 텍스트 (0) | 2020.07.15 |
유닉스에서 쉘 스크립트를 사용하여 10 일이 지난 파일 삭제 (0) | 2020.07.15 |
.BAT에서 사용중인 포트를 찾아 프로세스 종료 (0) | 2020.07.15 |
조각 내부 조각 (0) | 2020.07.15 |