Mic*_*ens 3 c# transparency overlay winforms
下面的代码演示了一个非常简单的问题; 我希望我只是错过了某人可能能够揭示的环境.
(1)启动主winform(MainForm).
(2)按下按钮显示半透明的二级winform(ShadowForm),并且应该完全覆盖MainForm.
场景1:启动主winform,然后按下按钮:ShadowForm显示正确的大小但不正确的位置,向下和向右(就像它是级联的).按按钮再次关闭ShadowForm.再按一次按钮重新打开ShadowForm,现在它处于正确位置,覆盖MainForm.
场景2:启动主winform,移动它,然后按下按钮:ShadowForm显示正确的大小但位置不正确(MainForm在移动之前的位置).按按钮关闭; 再次按下重新打开,现在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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在第一次设置位置之前,应将StartPosition设置为手动.
shadowForm.StartPosition = FormStartPosition.Manual;
shadowForm.Size = Size; // this always works
shadowForm.Location = Location; // this fails first time, but works second time!
shadowForm.Show();
Run Code Online (Sandbox Code Playgroud)
或者像乔尔建议的那样:
shadowForm.StartPosition = FormStartPosition.CenterParent; // Location shouldn't need to be set
shadowForm.Size = Size; // this always works
shadowForm.Show();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
946 次 |
| 最近记录: |