Jurion
Jurion

Reputation: 1298

How do I make my entire game window transparent?

I’m working on a little overlay for Diablo 3 (For personal use only!) I want just to draw a Text string (We’ll see later for font) in the middle of the screen. But with XNA I cannot find how to put background to transparent… My code so far is :

        GraphicsDevice.Clear(new Color(0, 0, 0, 255));
        spriteBatch.Begin();
        spriteBatch.DrawString(font, this.TestToShow, new Vector2(23, 23), Color.White);
        spriteBatch.End();

So I only need 1 thing: make this black transparent!

Upvotes: 4

Views: 1810

Answers (1)

Max Play
Max Play

Reputation: 4037

You do not seem to understand what GraphicsDevice.Clear(Color) does. XNA opens a Windows Window and draws with DirectX into it.

GraphicsDevice.Clear(Color) clears the buffer drawn with DirectX, but doesn't have anything to do with the window. To make the window transparent, you have to modify the underlaying window.

To do that you have to first add references to System.WIndows.Forms and System.Drawing.

In the Constructor of your Game1 class, you do the following:

public Game1()
{
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";
    IntPtr hWnd = Window.Handle;
    System.Windows.Forms.Control ctrl = System.Windows.Forms.Control.FromHandle(hWnd);
    System.Windows.Forms.Form form = ctrl.FindForm();
    form.TransparencyKey = System.Drawing.Color.Black;
}

Let's go through this line by line:

Well, the first two are auto generated and we don't care about these.

IntPtr hWnd = Window.Handle;

This line gets you the pointer to the underlaying Window that is registered in Windows.

System.Windows.Forms.Control ctrl = System.Windows.Forms.Control.FromHandle(hWnd);

This line gets the WindowsForms-Control in the given Window.

System.Windows.Forms.Form form = ctrl.FindForm();

This line gets you the Form to which the Control belongs to.

form.TransparencyKey = System.Drawing.Color.Black;

This last line sets the key-Color, that identifies one single Color-value to not be drawn at all. I used Black, but you could also choose CornflowerBlue.

This makes your window internally transparent for that Color. I suggest you should choose the same Color as your clear-Color.

Two things to note:

  1. Best practice is to cache your Form so you can set the TransparencyKey from anywhere.

  2. You can also make your Window borderless this way:

form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

Hope I could help.

Edit: I just realized this was asked years ago and had no answer. So feel free to use this, if you stumble upon it.

Upvotes: 4

Related Questions