IntPtr win = GetActiveWindow();
RECT dimensions;
GetWindowRect(win, out dimensions);
上面的代码似乎返回一个矩形,其尺寸为0。右和尺寸。左边的值。我对winapi的提及如下。
[DllImport("user32.dll", SetLastError=true)]
static extern IntPtr GetActiveWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
enum GetWindow_Cmd : uint
{
GW_HWNDFIRST = 0,
GW_HWNDLAST = 1,
GW_HWNDNEXT = 2,
GW_HWNDPREV = 3,
GW_OWNER = 4,
GW_CHILD = 5,
GW_ENABLEDPOPUP = 6
}
[DllImport("user32.dll", SetLastError=true))]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
GetActiveWindow似乎没有返回用户当前选择的窗口。我注意到,如果我将以上内容更改为以下内容似乎可以正常工作。
IntPtr win = GetForegroundWindow();
RECT dimensions;
GetWindowRect(win, out dimensions);
编辑:带支票的代码。
IntPtr win = GetActiveWindow();
if (win == IntPtr.Zero)
{
//this triggers
Debug.WriteLine("Win: " + win.ToString());
Debug.WriteLine("Unable to get window handle.");
}
else
{
RECT dimensions;
uint pid;
GetWindowThreadProcessId(win, out pid);
Debug.WriteLine(Marshal.GetLastWin32Error().ToString());
Debug.WriteLine(pid.ToString());
if (GetWindowRect(win, out dimensions))
{
Debug.WriteLine(dimensions.Top.ToString() + ", " + dimensions.Right.ToString() + ", "
+ dimensions.Bottom.ToString() + ", " + dimensions.Left.ToString() + "\nPID: " + pid.ToString());
ScreenCapture sc = new ScreenCapture();
int width = dimensions.Right - dimensions.Left;
int height = dimensions.Bottom - dimensions.Top;
Clipboard.SetImage(sc.CaptureArea(dimensions.Left, dimensions.Top, width, height));
}
else
{
Debug.WriteLine(Marshal.GetLastWin32Error().ToString() + "\nPID:" + pid.ToString());
Debug.WriteLine("Unable to get window dimensions.\nPID:" + pid.ToString());
}
}
SSCCE:
using System;
using System.Runtime.InteropServices;
namespace GetWindow
{
class Program
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetActiveWindow();
static void Main(string[] args)
{
IntPtr win = GetActiveWindow();
Console.WriteLine("Win: " + win.ToString()); //outputs 0 to console
Console.Read();
}
}
}
答案 0 :(得分:7)
这很正常。 GetActiveWindow
获取调用线程的活动窗口。如果调用线程不拥有前台窗口,则GetActiveWindow
将返回NULL
。