这是我的代码:
public string selectedProgram;
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, Rectangle rect);
private void button2_Click(object sender, EventArgs e)
{
Process[] process = Process.GetProcesses();
foreach (var p in process)
{
selectedProgram = listView1.SelectedItems.ToString();
Rectangle bonds = new Rectangle();
GetWindowRect(Handle, bonds);
Bitmap bmp = new Bitmap(bonds.Width, bonds.Height);
using (var gfx = Graphics.FromImage(bmp))
{
gfx.CopyFromScreen(bonds.Location, Point.Empty, bonds.Size);
pictureBox1.Image = bmp;
frm2.Show();
frm2.pictureBox1.Image = pictureBox1.Image;
}
}
我在GetWindowRect(Handle, bonds);
上收到错误或绿色突出显示:
A call to PInvoke function 'Screen Shot!WindowsFormsApplication1.Form3::GetWindowRect' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.
我如何解决此问题,以便获取其他应用程序窗口的屏幕截图?
答案 0 :(得分:1)
您的声明缺少'out'并使用错误的矩形类型,它应如下所示:
private static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
你称之为:
GetWindowRect(Handle, out bonds);
Rectangle也需要是WinApi矩形,而不是.net类。有关其定义,请参阅here。惯例是将其称为RECT而不是Rectangle。
答案 1 :(得分:1)
查看pinvoke.net(精彩参考),签名GetWindowRect
应为:
public static extern bool GetWindowRect(HandleRef hwnd, out RECT lpRect);
它也可能会这样做,这不需要您定义自定义RECT
结构:
public static extern bool GetWindowRect(IntPtr hwnd, out Rectangle lpRect);
如果这不起作用,您可以根据this page定义RECT
结构,并使用:
public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
RECT
上的pinvoke.net页面显示了如何在RECT
和Rectangle
之间进行转换。