何がWinフォームの位置が最初に古いのですか?
-
13-09-2019 - |
質問
以下のコードは非常に単純な問題を示しています。私はちょうど誰かが明らかにすることができるかもしれないという設定をしないのですことを期待しています。
目標
(1)主Winフォーム(MainFormを)を起動。
(2)半透明であるべきであり、正確にオーバーレイMainFormを二次Winフォーム(ShadowForm)を表示するための押しボタンを
何
シナリオ1 :正しいサイズが、誤った場所、下および右(それがカスケード接続されたかのような)へとShadowForm表示:ボタンを押しメインWinフォームを起動します。 ボタンを押すと、再びShadowFormを閉じます。押しボタンをもう一度ShadowFormを再開するために、今ではMainFormををカバーし、正しい位置にある。
シナリオ2 :(MainFormをそれを移動する前であった場合)、正しいサイズが、誤った場所でShadowForm表示:ボタンを押し、メインWinフォームを起動周りに移動します。ボタンを押すと閉じます。もう一度押すと、再度開くと、今ShadowFormすることが正しい位置にある。
using System;
using System.Windows.Forms;
namespace LocationTest
{
static class Program
{
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
public class MainForm : Form
{
ShadowForm shadowForm = new ShadowForm();
Button button1 = new Button();
System.ComponentModel.IContainer components = null;
public MainForm()
{
this.SuspendLayout();
this.button1.Location = new System.Drawing.Point(102, 44);
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.button1);
this.ResumeLayout(false);
}
private void button1_Click(object sender, EventArgs e)
{
if (shadowForm.Visible) { shadowForm.Hide(); }
else
{
shadowForm.Size = Size; // this always works
shadowForm.Location = Location; // this fails first time, but works second time!
shadowForm.Show();
}
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null)) { components.Dispose(); }
base.Dispose(disposing);
}
}
public class ShadowForm : Form
{
private System.ComponentModel.IContainer components = null;
public ShadowForm()
{
this.SuspendLayout();
this.BackColor = System.Drawing.Color.Black;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Opacity = 0.5;
this.Click += new System.EventHandler(this.ShadowForm_Click);
this.ResumeLayout(false);
}
private void ShadowForm_Click(object sender, EventArgs e)
{
Hide();
}
protected override void Dispose(bool disposing)
{
if (disposing && (components != null)) { components.Dispose(); }
base.Dispose(disposing);
}
}
}
解決
あなたは開始位置マニュアルへのあなたの場所最初の時間を設定する前に。
shadowForm.StartPosition = FormStartPosition.Manual;
shadowForm.Size = Size; // this always works
shadowForm.Location = Location; // this fails first time, but works second time!
shadowForm.Show();
やジョエルが示唆されているように:
shadowForm.StartPosition = FormStartPosition.CenterParent; // Location shouldn't need to be set
shadowForm.Size = Size; // this always works
shadowForm.Show();
所属していません StackOverflow