Search code examples
c#wpfwinformstransparency

How do I make my form transparent, but what I draw on it not?


I tried setting the opacity of my form to 50%, and then drawing a string on it. It seems that the string I draw on it also has an opacity of 50%. How would I draw a non transparent string , but let the form background show through 50%?

Would also be willing to do this in WPF if it is possible, but I would need explicit instructions or an example project as I have never done it before.

To clarify, I want the form background to be a black 80% opaque to what is underneath, and then I want to draw text, etc.. on it and have it appear 100% opaque.


Solution

  • This is very easily done in WPF:

    1. Set WindowStyle="None" on the Window (note: this is required, you cannot have Transparency and the standard windows chrome)
    2. Set AllowsTransparency="True" on the Window
    3. Set a Background on the Window using a brush with transparency, such as Background="#AAFFFFFF"

    Here's a quick sample:

    <Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Height="300" Width="300" AllowsTransparency="True" Background="#AAFFFFFF" WindowStyle="None">
    <Grid>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="20" FontWeight="Bold">Hello World!</TextBlock>
    </Grid>
    

    Now obviously, since you've disabled the standard Windows chrome, you will need to supply your own button to close/minimize/maximize/drag the window. You can do this pretty easily yourself or you could look into purchasing something like Blendables which comes with a "Chromeless Window" control that you could use.