Search code examples
vb.netformsmodal-dialogtouchscreen

Darken a .Net Form


I have a 1080p touchscreen application. When a modal pops up, i want to emphasize that by darkening the main form.

Right now i use a second form, the size of the main form, that is black and has 50% opacity. Whenever a modal needs to appear, i open the opaque form, and then open the desired modal.

I feel this is a bit devious for my purpose. Its also not asshole-proof that when the user alt tabs, the forms will glitch out of sequence.

Is there a better way to achieve the darkening effect. Perhaps by darkening the main form from within itself?


Solution

  • Here is some code, very similar to the method in Thomas's answer. Note to use the Darkness property in a Try...Finally block, to make sure you never leave the form in the dark state.

    Public Class Form1
    
    
    Private _PB As PictureBox
    
    Public WriteOnly Property Darkness
        Set(value)
            If value Then
                Dim Bmp = New Bitmap(Bounds.Size.Width, Bounds.Size.Height)
                Me.DrawToBitmap(Bmp, New Rectangle(Point.Empty, Bounds.Size))
                Using g = Graphics.FromImage(Bmp)
                    Dim Brush As New SolidBrush(Color.FromArgb(125, Color.Black))
                    g.FillRectangle(Brush, New Rectangle(Point.Empty, Bmp.Size))
                End Using
                _PB = New PictureBox
                Me.Controls.Add(_PB)
                _PB.Size = Bounds.Size
                _PB.Location = Bounds.Location - PointToScreen(Point.Empty)
                _PB.Image = Bmp
                _PB.BringToFront()
            Else
                If _PB IsNot Nothing Then
                    Me.Controls.Remove(_PB)
                    _PB.Dispose()
                End If
            End If
        End Set
    End Property
    
    Private Sub btnDialog_Click(sender As Object, e As EventArgs) Handles btnDialog.Click
        Try
            Darkness = True
    
            MsgBox("Modal dialog")
    
        Finally
            Darkness = False
        End Try
    End Sub
    End Class