can't I set transparency of a window by its handle in c#?

纵饮孤独 提交于 2019-12-07 14:01:28

问题


i am trying to set transparency of all windows. I have following code.

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

    [DllImport("user32.dll")]
    static extern int GetWindowLong(IntPtr hWnd, int nIndex);

    [DllImport("user32.dll")]
    static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);

    public const int GWL_EXSTYLE = -20;
    public const int WS_EX_LAYERED = 0x80000;
    public const int LWA_ALPHA = 0x2;

    public Form1()
    {
        InitializeComponent();
        this.Load += new EventHandler(Form1_Load);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Process[] processlist = Process.GetProcesses();

        foreach (Process theprocess in processlist)
        {
            SetWindowLong(theprocess.Handle, GWL_EXSTYLE,
                GetWindowLong(theprocess.Handle, GWL_EXSTYLE) ^ WS_EX_LAYERED);
            SetLayeredWindowAttributes(theprocess.Handle, 0, 128, LWA_ALPHA);
        }

    }
}

nothing happens when I execute the code.

What is wrong??


回答1:


SetWindowLong takes a window handle (hWnd), but you're passing it a process handle instead. Change all instances of

theprocess.Handle

to

theProcess.MainWindowHandle

After changing that, it worked on the Windows XP machine I tested it on. Now I'm gonna have to modify the code to get the windows back to normal ;) Luckily, the Visual Studio 2010 window was unaffected.




回答2:


This part of your code:    ^ WS_EX_LAYERED   flips the WS_EX_LAYERED bit,

I think you want:    | WS_EX_LAYERED




回答3:


Have you tried setting the Opacity?

this.Opacity = 0.50;


来源:https://stackoverflow.com/questions/1270316/cant-i-set-transparency-of-a-window-by-its-handle-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!