调光无活性形式调光、活性、形式

2023-09-03 04:29:05 作者:社会狗多ゞ别被咬

在打开使用Form.ShowDialog()我想用灰色阴影黯淡的应用程序的其他部分对话的形式。

When opening Dialog form using Form.ShowDialog() I want to dim the rest of application with a shade of gray.

这是我自己的研究似乎做的方式是开黑色背景和不透明度小于100%,无边框形式,但我并没有把所有的拼在一起,将如何工作,或者如果它是最好的方法去做吧。

From my own research it seems that the way to do it is to open a borderless form with black background and opacity less than 100% but I haven't put all the pieces together how it would work or if it's the best way to do it.

任何建议将是有益的。 谢谢你。

Any suggestions would be helpful. Thanks.

推荐答案

这是最好的覆盖在打开的窗体用另一种形式的无国界的和相同的尺寸做的。这允许你这样做让整个造型看起来禁用,包括控制和标题栏。添加一个新类到您的项目并粘贴此code:

This is best done by overlaying the open forms with another form that's borderless and the same size. This allows you do make the entire form look disabled, including the controls and the title bar. Add a new class to your project and paste this code:

using System;
using System.Drawing;
using System.Collections.Generic;
using System.Windows.Forms;

class DialogOverlay : IDisposable {
    public DialogOverlay() {
        var cnt = Application.OpenForms.Count;
        for (int ix = 0; ix < cnt; ++ix) {
            var form = Application.OpenForms[ix];
            var overlay = new Form { Location = form.Location, Size = form.Size, FormBorderStyle = FormBorderStyle.None,
                ShowInTaskbar = false, StartPosition = FormStartPosition.Manual, AutoScaleMode = AutoScaleMode.None };
            overlay.Opacity = 0.3;
            overlay.BackColor = Color.Gray;
            overlay.Show(form);
            forms.Add(overlay);
        }
    }
    public void Dispose() {
        foreach (var form in forms) form.Close();
    }
    private List<Form> forms = new List<Form>();
}

和使用这样的:

    private void DialogButton_Click(object sender, EventArgs e) {
        using (new DialogOverlay()) 
        using (var dlg = new Dialog()) {
            if (dlg.ShowDialog(this) == DialogResult.OK) {
                // etc...
            }
        }
    }

扭捏的不透明度和背景色属性来调整效果。它适用于任何形式的对话,包括内置的像打开文件对话框,以及任何一套开放的形式在您的应用程序。要注意的是Application.OpenForms是一丁点儿的越野车。

Tweak the Opacity and BackColor properties to adjust the effect. It will work with any kind of dialog, including the built-in ones like OpenFileDialog, and any set of open forms in your application. Beware that Application.OpenForms is a wee bit buggy.