我正在尝试获取桌面中特定区域(应用程序)的屏幕截图。请检查此代码...
try
{
//Process p = Process.Start("notepad");
//Process p = Process.GetProcessById(11152);
if (p == null)
Console.WriteLine("Got Null");
else
{
IntPtr h = p.Handle;
SetForegroundWindow(h);
ShowWindow(h, 9);
Rect rect = new Rect();
IntPtr error = GetWindowRect(p.MainWindowHandle, ref rect);
while (error == (IntPtr)0)
{
error = GetWindowRect(p.MainWindowHandle, ref rect);
}
Thread.Sleep(2000);
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
System.IO.FileStream fs = System.IO.File.Create(@"D:\snapshot.jpg");
Bitmap bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics.FromImage(bitmap).CopyFromScreen(rect.left, rect.top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy);
bitmap.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
fs.Close();
bitmap.Dispose();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
我在这个方法之外有这个..
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern IntPtr ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);
[StructLayout(LayoutKind.Sequential)]
public struct Rect
{
public int left;
public int top;
public int right;
public int bottom;
}
当我尝试打开一个新的应用程序并尝试截取屏幕截图(例如本例中的记事本)时,它就像一个超级按钮。但是,当我尝试拍摄当前正在运行的应用程序(如任务管理器等)的屏幕截图时,它不起作用(我仍然得到一个黑色小矩形的图像)..请帮助我。
改变
IntPtr h = p.Handle;
到
IntPtr h = p.MainWindowHandle;
并检查。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句