界面
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="255,174,0,0" VerticalAlignment="Top" Click="Button_Click"/>
</Grid>
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MyScreenCapture;
namespace 窗体截图
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ScreenCapture.GetWindow(ScreenCapture.GetWindowHwndSource(this), this).Save("./a.bmp");
}
}
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using 窗体截图;
namespace MyScreenCapture
{
public class ScreenCapture
{
/// <summary>
/// 主窗体句柄
/// </summary>
public static System.Windows.Interop.HwndSource Hwnd;
/// <summary>
/// 获取窗体句柄
/// </summary>
/// <param name="window">窗体</param>
public static IntPtr GetWindowHwndSource(DependencyObject window, bool isHwnd = true)
{
var formDependency = System.Windows.Interop.HwndSource.FromDependencyObject(window);
System.Windows.Interop.HwndSource winformWindow = (formDependency as System.Windows.Interop.HwndSource);
if (isHwnd)
Hwnd = winformWindow;
return winformWindow.Handle;
}
public static Bitmap GetWindow(IntPtr hWnd, MainWindow w1)
{
IntPtr hscrdc = GetWindowDC(hWnd);
IntPtr hbitmap = CreateCompatibleBitmap(hscrdc, (int)w1.Width, (int)w1.Height);
IntPtr hmemdc = CreateCompatibleDC(hscrdc);
SelectObject(hmemdc, hbitmap);
PrintWindow(hWnd, hmemdc, 0);
Bitmap bmp = Bitmap.FromHbitmap(hbitmap);
DeleteDC(hscrdc);
DeleteDC(hmemdc);
return bmp;
}
[DllImport("gdi32.dll")]
static extern IntPtr DeleteDC(IntPtr hDc);
[DllImport("gdi32.dll")]
static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);
[DllImport("gdi32.dll")]
static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr ptr);
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, UInt32 nFlags);
}
}