Это было нелегко. Ниже приведен рабочий пример с использованием WPF и WinForms.
Я обнаружил, что при масштабировании дисплея в соответствии с настройками ОС он начинает работать при работе с необработанной графикой (относительно координат / размеров).
В примере WPF я назвал это SCALE_FACTOR
. Поскольку моя шкала windows установлена на 150%, я масштабируюсь с коэффициентом 1.5
. Пример WPF работает тогда для меня:
Пример WPF:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private const double SCALE_FACTOR = 1.5; // 150% in windows 10 settings
private void button_Click(object sender, RoutedEventArgs e)
{
// take window location
var x = (int)(Application.Current.MainWindow.Left);
var y = (int)(Application.Current.MainWindow.Top);
// convert to System.Drawing.Point
var currentLocationPoint = new System.Drawing.Point(x, y);
CaptureImage(
// current TOP, LEFT location of the window on the screen
currentLocationPoint,
// TOP, LEFT location of the destination
new System.Drawing.Point(0, 0),
// size of the current window AND of the destination window/buffer/image
new System.Drawing.Rectangle(
0,
0,
// need to scale the width because of the OS scaling
(int)(this.ActualWidth * SCALE_FACTOR),
// need to scale the heigt because of the OS scaling
(int)(this.ActualHeight * SCALE_FACTOR)),
@"c:\temp\screen.bmp");
}
public static void CaptureImage(System.Drawing.Point SourcePoint, System.Drawing.Point DestinationPoint, System.Drawing.Rectangle SelectionRectangle, string FilePath)
{
// create new image with the specified size = current window size
using (Bitmap bitmap = new Bitmap(SelectionRectangle.Width, SelectionRectangle.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(
// X start for copy is current window LEFT - scaled
(int)(SourcePoint.X * SCALE_FACTOR),
// Y start for copy is current window TOP - scaled
(int)(SourcePoint.Y * SCALE_FACTOR),
// X start in destination window is 0
0,
// Y start in destination window is 0
0,
// size of destination window is the same as the current window
SelectionRectangle.Size);
}
bitmap.Save(FilePath, ImageFormat.Bmp);
}
}
}
Windows Пример форм:
В моем тесте windows имеет размер (250,250)
в пикселях.
SourcePoint
- начало, поэтому оно должно быть на самом деле (0,0)
. DestinationSize - это высота и ширина - вам не нужны преобразования.
//CaptureImage(this.Location, new Point(0, 0), new Rectangle(0, 0, 250, 250), @"c:\temp\screen.bmp");
CaptureImage(this.Location, new System.Drawing.Point(0, 0), new Rectangle(this.Location.X, this.Location.Y, this.Width , this.Height),@"c:\temp\screen.bmp");

