为什么当我关闭控件时,Form1没有回到CenterScreen位置?

时间:2012-10-29 09:08:41

标签: c#

private void histogramGraphsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Location = new Point(0, 0);
            HistogramGraphs1 = new Lightnings_Extractor.Histogram_Graphs();
            HistogramGraphs1.Show();
            HistogramGraphs1.FormClosing += new FormClosingEventHandler(HistogramGraphs1_FormClosing);
            histogramGraphsToolStripMenuItem.Enabled = false;

        }



private void HistogramGraphs1_FormClosing(object sender , FormClosingEventArgs e)
    {
        this.StartPosition = FormStartPosition.CenterScreen;
        histogramGraphsToolStripMenuItem.Enabled = true;
    }

我第一次将表格放在0,0位置 然后在Closing事件中我希望它返回到中心屏幕,但Form仍然在0,0位置。

我该如何解决?

2 个答案:

答案 0 :(得分:1)

首先通过设置e.Cancel = true来阻止关闭此表单。然后将窗口移动到屏幕中心:

private void HistogramGraphs1_FormClosing(object sender , FormClosingEventArgs e)
{
    histogramGraphsToolStripMenuItem.Enabled = true;
    e.Cancel = true;
    int x = Screen.PrimaryScreen.WorkingArea.Width / 2 - this.Width / 2;
    int y = Screen.PrimaryScreen.WorkingArea.Height / 2 - this.Height / 2;
    this.Location = new Point(x, y);
}

这篇MSDN文章可能很有用:

解释

  

CancelEventArgs.Cancel:获取或设置一个值,指示是否应取消该事件。

     

Form.Location Property:获取或设置表示屏幕坐标中表单左上角的Point。

答案 1 :(得分:0)

如果您设置this.StartPosition = FormStartPosition.CenterScreen;然后你需要重新打开表格。否则它不会起作用。