c# - 带不透明度的 WinForm 控件

标签 c# winforms opacity

我有一个表单,它本身有一些控件(btnCreateReport,pnlDarkLayer)。我有一个适合表单的面板(Dock = Fill),它位于所有控件的背面。当用户单击 btnCreateReport 按钮时,我调用 pnlDarkLayer BringToFront 方法,经过一些计算我调用按钮的 SendToBack() 方法。我想在表单控件上绘制一个深色层并禁用表单上的所有控件。 是否可以?谢谢。

也许这段代码可以帮助您理解我的目的:

private void btnCreateReport_Click(object sender, EventArgs e)
{
    pnlDarkLayer.BackColor = Color.FromArgb(100, Color.Gray);         

    pnlDarkLayer.BringToFront();
    btnCreateReport.Enabled = false;

    Thread ProcessReport = new Thread(new ThreadStart(ProcessingReport));
    ProcessReport.Start();
    while (ProcessReport.IsAlive)
    {
        Application.DoEvents();
    }
    pnlDarkLayer.SendToBack();

    btnCreateReport.Enabled = true;

}

这段代码隐藏了所有控件,但我不想隐藏窗体上的控件。我想在它们上面画一个深色层。用户必须可以看到控件。 我需要一些类似窗体不透明度属性的控件。

我已经测试过了:

pnlDarkLayer.CreateGraphics().CompositingMode=System.Drawing.Drawing2D.CompositingMode.SourceOver;

更新:我已经测试了这个:(使用表单而不是面板)

private void btnCreateReport_Click(object sender, EventArgs e)
{          

    btnCreateReport.Enabled = false;

    frmProgress ProgressForm = new frmProgress();
    ProgressForm.TopLevel = false;
    ProgressForm.Parent = this;
    ProgressForm.BringToFront();
    this.Controls.Add(ProgressForm);
    ProgressForm.Show();

    Thread ProcessReport = new Thread(new ThreadStart(ProcessingReport));
    ProcessReport.Start();

    while (ProcessReport.IsAlive)
    {
        Application.DoEvents();
    }
    ProgressForm.Close();
    btnCreateReport.Enabled = true;

}

但是我在我的表单中看不到 ProgressForm。

最佳答案

来自 http://support.microsoft.com/kb/943454

Transparent controls in WinForms are transparent relative to their parent, not to other controls. Transparency in WinForms is more akin to camouflage than true transparency. A transparent control doesn’t actually let you see the control behind it through the form. It asks its parent to draw its own background on the "transparent" control. This is why a transparent control shows the form behind it, but covers up any other controls.

To implement transparency relative to other controls requires doing the same thing but on a larger scale: instead of just asking the parent to draw on the foreground control’s background, the control needs to ask all controls behind it to draw on its background. This will only work for controls which provide some method to request that they be drawn and will not automatically update when the background control’s image changes.

该页面还提供了一个代码示例(遗憾的是在 vb 中)来展示这是如何完成的。

关于c# - 带不透明度的 WinForm 控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6106449/

相关文章:

c# - DataGridViewTextBoxColumn 在数字单元格中添加逗号

javascript - 覆盖可点击的div

R散点图: symbol color represents number of overlapping points

c# - 将小端转换为 int

c# - 在 Windows 任务计划程序 C# 中计划任务

.net - 在绑定(bind)到字典的组合框中设置所选项目

CSS:Opacity - Div 在 IE7 中不显示?

c# - 连接到 WPF C# 应用程序远程 SQL 数据库

c# - 如何从 MahApps.Metro 将带有操作的按钮添加到 ShowInputAsync

c# - IDocHostUIHandler TranslateAccelerator 不允许键盘输入