November 30, 2011

Position A Form In The Center Of The Screen

Source code สำหรับจัดวางตำแหน่งของ Form ให้อยู่กึ่งกลางหน้าจอหลักของ Windows
int boundWidth = Screen.PrimaryScreen.Bounds.Width;
int boundHeight = Screen.PrimaryScreen.Bounds.Height;
int x = boundWidth - this.Width;
int y = boundHeight - this.Height;
this.Location = new Point(x / 2, y / 2);
ตัวอย่างการใช้งาน :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestCenterScreen
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int boundWidth = Screen.PrimaryScreen.Bounds.Width;
            int boundHeight = Screen.PrimaryScreen.Bounds.Height;
            int x = boundWidth - this.Width;
            int y = boundHeight - this.Height;
            this.Location = new Point(x / 2, y / 2);
        }
    }
}
เมื่อคลิกปุ่ม button1 แล้ว Form จะย้ายตำแหน่งมาที่กึ่งกลางจอ Windows ทันที สามารถเอาไปประยุกต์ใช้กับ Object อื่นๆ ที่อยู่ใน Form ได้ โดยเปลี่ยน 
this.Width 
this.Height 
this.Location 
เป็น 
objectName.Width 
objectName.Height 
objectName.Location

No comments:

Post a Comment