加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何将表单设置为屏幕中心?

发布时间:2020-12-16 01:52:03 所属栏目:百科 来源:网络整理
导读:我正在使用此代码: private void notifyIcon1_MouseDoubleClick(object sender,MouseEventArgs e){ this.Show(); this.WindowState = FormWindowState.Normal; //this.Location = new Point(form1_location_on_x,form1_location_on_y); //this.StartPositio
我正在使用此代码:

private void notifyIcon1_MouseDoubleClick(object sender,MouseEventArgs e)
{
    this.Show();
    this.WindowState = FormWindowState.Normal;
    //this.Location = new Point(form1_location_on_x,form1_location_on_y);
    //this.StartPosition = FormStartPosition.CenterScreen;

这条线

this.Location = new Point(form1_location_on_x,form1_location_on_y);

或者线

this.StartPosition = FormStartPosition.CenterScreen;

当我使用原始屏幕分辨率1920×1080时正在工作,但是一旦我将分辨率更改为1024×768,表格就在右下角没有隐藏我看到它全部但它不在中心.

form1_location_on_x和on_y是:

form1_location_on_x = this.Location.X;
form1_location_on_y = this.Location.Y;

问题是我应该怎样做才能使其适用于1024×768等任何其他分辨率?我尝试了很多改变但到目前为止没有任何效果

解决方法

您可以使用以下公式计算表单的顶部和左侧位置:

int formWidth = yourForm.Width;
int formHeight = yourForm.Height;
int screenH = (Screen.PrimaryScreen.WorkingArea.Top + 
              Screen.PrimaryScreen.WorkingArea.Height) / 2;
int screenW = (Screen.PrimaryScreen.WorkingArea.Left + 
              Screen.PrimaryScreen.WorkingArea.Width) / 2;

int top = screenH - formWidth / 2;
int left = screenW - formHeight / 2;
yourForm.Location = new Point(top,left);

当然,现在,你有双显示器的问题.
我不知道您是希望表单始终显示在主屏幕上,还是希望表单显示在当前屏幕(当前显示表单的那个屏幕)中.在第二种情况下,您需要找到表单的显示位置

private void CenterForm(Form yuorForm)
{    
    foreach(var s in Screen.AllScreens)
    {
       if(s.WorkingArea.Contains(yourForm.Location))
       {
            int screenH = s.WorkingArea.Height / 2;
            int screenW = s.WorkingArea.Width / 2;

            int top = (screenH + s.WorkingArea.Top) - formWidth / 2;
            int left = (screenW + s.WorkingArea.Left) - formHeight / 2;
            yourForm.Location = new Point(top,left);
            break;
       }
    }
}

编辑:感谢@alex,我将用SystemEvents课程的信息完成答案

如果您希望系统在用户突然更改屏幕分辨率时收到通知,您可以订阅事件SystemEvents.DisplaySettingsChanged(使用Microsoft.Win32;需要)

SystemEvents.DisplaySettingsChanged += new EventHandler(SystemEvents_DisplaySettingsChanged);

然后在事件中处理表单的重新定位

// This method is called when the display settings change.
void SystemEvents_DisplaySettingsChanged(object sender,EventArgs e)
{
    RecenterForm(yourForm);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读