WPF 获取点击屏幕的坐标
时间: 2023-09-15 08:20:01 浏览: 60
在 WPF 中,可以通过以下代码获取点击屏幕时的坐标:
```csharp
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Point point = e.GetPosition(this);
double x = point.X;
double y = point.Y;
// 处理点击事件
}
```
在上面的代码中,`Window_MouseLeftButtonDown` 是一个鼠标左键按下事件的处理程序。`e.GetPosition(this)` 方法可以获取相对于窗口左上角的坐标点。然后可以将这些坐标用于处理点击事件。
相关问题
WPF 使用GDI获取屏幕坐标
在WPF中,可以使用System.Windows.Forms命名空间中的Control类和Screen类来获取屏幕坐标。
首先需要添加对System.Windows.Forms的引用。
然后可以使用以下代码获取当前屏幕的大小:
```
System.Drawing.Rectangle screenBounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
```
接着,可以使用以下代码获取鼠标在屏幕上的位置:
```
System.Drawing.Point mousePosition = System.Windows.Forms.Control.MousePosition;
```
最后,可以使用以下代码将鼠标位置转换为WPF中的坐标:
```
System.Windows.Point wpfMousePosition = new System.Windows.Point(mousePosition.X, mousePosition.Y);
```
需要注意的是,使用System.Windows.Forms可能会导致一些兼容性问题。如果想要避免这些问题,可以考虑使用WPF自带的Mouse类和Screen类来获取屏幕坐标。
wpf 获取屏幕截图
在WPF中获取屏幕截图可以通过使用System.Windows.Forms命名空间中的Screen类和Bitmap类来实现。首先需要导入System.Drawing命名空间以及System.Drawing.Imaging命名空间。然后可以使用Screen类的FromPrimaryScreen方法获取主屏幕的大小和位置,并创建一个矩形对象来表示整个屏幕的区域。接下来使用Bitmap类的FromScreen方法传入屏幕区域来创建一个位图对象,然后可以使用Graphics对象的CopyFromScreen方法将屏幕的内容拷贝到位图中。最后可以使用位图对象的Save方法将屏幕截图保存到本地文件中。
具体的代码实现如下:
```csharp
using System;
using System.Windows;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
namespace WpfApplication
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CaptureScreen()
{
Screen screen = Screen.FromPrimaryScreen();
Rectangle screenBounds = screen.Bounds;
Bitmap bitmap = new Bitmap(screenBounds.Width, screenBounds.Height, PixelFormat.Format32bppArgb);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(screenBounds.Left, screenBounds.Top, 0, 0, screenBounds.Size);
bitmap.Save("screenshot.png", ImageFormat.Png);
}
}
}
```
通过调用CaptureScreen方法就可以在WPF应用程序中获取屏幕截图并保存为本地文件。