0

I have a form which I make click-through using the following function calls:

SetWindowLong(Handle, GWL_EXSTYLE, (IntPtr)(GetWindowLong(Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED ^ WS_EX_TRANSPARENT));
SetLayeredWindowAttributes(Handle, 0, 0xFF, LWA_ALPHA);

This works fine, however when I try to fade that window using the System.Windows.Forms.Form.Opacity property I get the following exception:

System.ComponentModel.Win32Exception (0x80004005): The parameter is not valid
   at System.Windows.Forms.Form.UpdateLayered()
   at System.Windows.Forms.Form.set_Opacity(Double value)

How can I achieve both things at the same time?

Jonas Kohl
  • 1,018
  • 1
  • 11
  • 28
  • Looks like 3rd parameter should be 0x80. See : http://www.pinvoke.net/default.aspx/user32/SetLayeredWindowAttributes.html – jdweng Dec 18 '18 at 12:34
  • @jdweng Setting the third parameter to `0x7F` sadly didn't change anything. – Jonas Kohl Dec 18 '18 at 12:36
  • Are you looking for something like [this](https://stackoverflow.com/a/39856049/3110834)? – Reza Aghaei Dec 18 '18 at 12:41
  • The pinvoke code confuzzles Winforms, it doesn't know that you created a layered window. You just don't need it at all, simply setting the Opacity property is enough to get Winforms to set the exstyle and make that SetLayeredWindowAttributes() call. If this is an attempt to eliminate flicker then be sure to not set Opacity to 1 (aka 100 in the Properties window), change it between 0 and 0.99 – Hans Passant Dec 18 '18 at 13:46

1 Answers1

0

The following works on a windows form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication30
{
    public partial class Form1 : Form
    {

        [DllImport("user32.dll", SetLastError = true)]
        static extern System.UInt32 GetWindowLong(IntPtr hWnd, int nIndex);
        [DllImport("user32.dll", EntryPoint = "SetWindowLong")]
        private static extern int SetWindowLong32(IntPtr hWnd, int nIndex, uint dwNewLong);
        [DllImport("user32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
        static extern int SetLayeredWindowAttributes(IntPtr hWnd, int crKey, byte bAlpha, uint dwFlags);



        public const int GWL_EXSTYLE = -20;
        public const uint WS_EX_LAYERED = 0x80000;
        public const uint LWA_ALPHA = 0x2;
        public const uint LWA_COLORKEY = 0x1;
        public Form1()
        {
            InitializeComponent();

            IntPtr Handle = this.Handle;
            UInt32 windowLong = GetWindowLong(Handle, GWL_EXSTYLE);
            SetWindowLong32(Handle, GWL_EXSTYLE, (uint)(windowLong ^ WS_EX_LAYERED));
            SetLayeredWindowAttributes(Handle, 0, 128, LWA_ALPHA);
        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20