C#获取活动窗口
非常紧急的一个问题,大家请帮忙!
如何用C#获取在任务栏上的窗口的句柄,然后把我想留得留着,别的都关掉!
------解决方案--------------------使用Win32 API
//列举所有窗口
[DllImport( "user32.dll ", EntryPoint= "EnumWindows ")]
public static extern int EnumWindows(EnumWindowsCallback callback, int lParam);
public delegate bool EnumWindowsCallback(int hWnd, int lParam) ;//EnumWindows的回调函数
//判断窗口句柄是否有效
[DllImport( "user32.dll ",EntryPoint = "IsWindow ")]
public static extern bool IsWindow(int hWnd);
//判断窗口是否可见
[DllImport( "user32.dll ", EntryPoint= "IsWindowVisible " )]
public static extern bool IsWindowVisible(int hwnd);
------解决方案--------------------任务栏的类型是ToolbarWindow32
先获取任务栏的HANDLE 然后再获取里面的子控件
------解决方案--------------------如果仅是获取当前系统的活动的窗口,可以用这个API:
[DllImport( "user32.dll ", CharSet=CharSet.Auto, ExactSpelling=true)]
public static extern IntPtr GetForegroundWindow();
------解决方案--------------------给你一段取子控件的c++代码参考
void EnableToolbarWindow32(HWND hwnd)
{
//Windows用的是这个类型的
int count = ::SendMessage(hwnd,TB_BUTTONCOUNT,0,0);
for(int i=0;i <count;i++)
{
TBBUTTON tb;
::ZeroMemory(&tb,sizeof(TBBUTTON));
//获取ID
DWORD dwprocessID;
::GetWindowThreadProcessId(hwnd,&dwprocessID);
HANDLE hProcess = ::OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, false, dwprocessID);
LPVOID baseAddress = ::VirtualAllocEx(hProcess,NULL,sizeof(TBBUTTON),MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
::SendMessage(hwnd,TB_GETBUTTON,i,(LPARAM)baseAddress);
::ReadProcessMemory(hProcess,baseAddress,&tb,sizeof(tb),0);
::SendMessage(hwnd,(UINT)TB_ENABLEBUTTON,(WPARAM)tb.idCommand,(LPARAM)MAKELONG(TRUE,0));
if(tb.fsStyle == 16 || tb.fsStyle == 24)
{
//弹出的是什么?
}
::VirtualFreeEx(hProcess,baseAddress,0,MEM_RELEASE);
::CloseHandle(hProcess);
}
}
------解决方案--------------------using System.Diagnostics;
Process[] vProcesses = Process.GetProcesses();
foreach (Process vProcess in vProcesses)
if (vProcess.MainWindowHandle != IntPtr.Zero)
textBox1.AppendText(vProcess.ProcessName + "\r\n ");