C# 设置其它程序窗口的透明度
请教各位,用C#怎么实现像PeekThrough这个程序一样,可以把其它程序的窗口设置成半透明的?万分感谢。...
请教各位,用C# 怎么实现像Peek Through 这个程序一样,可以把其它程序的窗口设置成半透明的?万分感谢。
展开
1个回答
展开全部
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace DebugTaskCS
{
public partial class Form1 : Form
{
[DllImport("user32.dll", SetLastError = true)]
static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
[DllImport("user32.dll", SetLastError = true)]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
public Form1()
{
InitializeComponent();
// 所有标题为Form1的都调整(不包括自己,因为此时自己还没有显示,
// 当初始化完毕后连自己都会调整)
// 其实这个WindowsEnumerator只是枚举窗口句柄
// 如果只要某个特定窗口,获取他的窗体句柄就好了
// MakeWindowTransparent(句柄, 透明度);
foreach (var item in WindowsEnumerator.GetWindowHandles("Form1"))
MakeWindowTransparent(item, 128); // 0~255 128是50%透明度
}
// hWnd是句柄,factor是透明度0~255
bool MakeWindowTransparent(IntPtr hWnd, byte factor)
{
const int GWL_EXSTYLE = (-20);
const uint WS_EX_LAYERED = 0x00080000;
int Cur_STYLE = GetWindowLong(hWnd, GWL_EXSTYLE);
SetWindowLong(hWnd, GWL_EXSTYLE, (uint)(Cur_STYLE | WS_EX_LAYERED));
const uint LWA_COLORKEY = 1;
const uint LWA_ALPHA = 2;
const uint WHITE = 0xffffff;
return SetLayeredWindowAttributes(hWnd, WHITE, factor, LWA_COLORKEY | LWA_ALPHA);
}
}
// 枚举窗体
public static class WindowsEnumerator
{
private delegate bool EnumWindowsProc(IntPtr windowHandle, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool EnumWindows(EnumWindowsProc callback, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool EnumChildWindows(IntPtr hWndStart, EnumWindowsProc callback, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowTextLength(IntPtr hWnd);
private static List<IntPtr> handles = new List<IntPtr>();
private static string targetName;
public static List<IntPtr> GetWindowHandles(string target)
{
targetName = target;
EnumWindows(EnumWindowsCallback, IntPtr.Zero);
return handles;
}
private static bool EnumWindowsCallback(IntPtr HWND, IntPtr includeChildren)
{
StringBuilder name = new StringBuilder(GetWindowTextLength(HWND) + 1);
GetWindowText(HWND, name, name.Capacity);
if (name.ToString() == targetName)
handles.Add(HWND);
EnumChildWindows(HWND, EnumWindowsCallback, IntPtr.Zero);
return true;
}
}
}
运行效果:
追问
没想到这么快就遇到高手了,非常感谢你的热心帮助。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询