我刚刚用C#写了一个小程序,在我的桌面上显示引语。我的问题是如何将应用程序的窗口居中。为了计算所需的窗口位置,我使用以下公式:
Left = (Screen.PrimaryScreen.Bounds.Width - this.ActualWidth) / 2;
Top = (Screen.PrimaryScreen.Bounds.Height - this.ActualHeight) / 2;
不幸的是,如您在截图中所见,this.ActualWidth和this.ActualHeight给出了错误的值,分别为188.4和189,而不是1000(+)。
http://www.directupload.net/file/d/4044/4x2tgadg_png.htm
这里是GUI:
http://www.directupload.net/file/d/4044/63rx2sul_png.htm
文本形式的代码:
public partial class QuotePresenter : Window
{
public QuotePresenter()
{
InitializeComponent();
setSize();
}
private void setSize()
{
MaxWidth = Screen.PrimaryScreen.Bounds.Width * 0.8;
MaxHeight = Screen.PrimaryScreen.Bounds.Height * 0.8;
}
private void setLocation()
{
Left = (Screen.PrimaryScreen.Bounds.Width - this.ActualWidth) / 2;
Top = (Screen.PrimaryScreen.Bounds.Height - this.ActualHeight) / 2;
System.Windows.MessageBox.Show("Actual Width: " + this.ActualWidth + "\nWidth: " + this.Width);
}
public void SetQuote(Quotation quote)
{
Dispatcher.Invoke(new Action(() =>
{
tb_content.Text = quote.Content;
tb_author.Text = "- " + quote.Author;
setLocation();
}));
}
}
有人能告诉我这里出了什么问题吗?
提前感谢!