【问题标题】:Getting bounds of another application in C#?在 C# 中获取另一个应用程序的边界?
【发布时间】:2012-07-09 22:12:35
【问题描述】:

这是我的代码:

 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.

如何解决这个问题,以便获取其他应用程序窗口的屏幕截图?

【问题讨论】:

标签: c# winforms screenshot visual-c#-express-2010


【解决方案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 之间进行转换。

【讨论】:

  • 好的,我到家去看看
【解决方案2】:

您的声明缺少“out”并且使用了错误的矩形类型,应该如下:

private static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);

你用它来称呼它:

GetWindowRect(Handle, out bonds);

Rectangle 还需要是 WinApi 矩形,而不是 .net 类。有关其定义,请参见 here。惯例是称它为 RECT 而不是 Rectangle。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多