Dimming inactive forms

前端 未结 3 1384
囚心锁ツ
囚心锁ツ 2021-01-16 13:36

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

From my own research it seems that the way to do it is

3条回答
  •  广开言路
    2021-01-16 14:27

    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
    forms = new List(); }

    And use it like this:

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

    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.

提交回复
热议问题