测试鼠标指针所在的屏幕

时间:2015-02-07 05:57:57

标签: c# .net windows

我是JS / Node开发人员,我没有C#经验。我认为编写一个我可以从节点运行以获取屏幕截图的exe非常简单。问题是我只对鼠标光标当前所在的屏幕感兴趣。我找到了以下代码来截取屏幕截图,但它只处理主屏幕。

Rectangle bounds = Screen.GetBounds(Point.Empty);

System.Diagnostics.Debug.WriteLine("asdf " + bounds.ToString());

using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
    }
    bitmap.Save("test.jpg", ImageFormat.Jpeg);
}

有没有办法检测鼠标光标在哪个屏幕上并截取屏幕截图?

2 个答案:

答案 0 :(得分:2)

Welp:P结果就像将GetBounds中的点更改为鼠标位置而CopyFromScreen更改为从正确位置开始一样简单:

Rectangle bounds = Screen.GetBounds(Cursor.Position);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        g.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size);
    }
    bitmap.Save("cap.png", ImageFormat.Png);
}

答案 1 :(得分:1)

这里我获得了全局鼠标位置,并将其设置为矩形。

然后我检查了每个屏幕边界,如果鼠标位置与它相交。

从那里我有了活动屏幕所以我只需要截取屏幕截图。 希望这会对你有所帮助。

private void takeScreenshot()
    {
        Bitmap screenshot;
        Graphics graphics;

        Rectangle mousePoint = new Rectangle(Cursor.Position, new Size(1, 1));

        Screen activeScreen = null;

        foreach (Screen s in Screen.AllScreens)
        {
            if (s.Bounds.IntersectsWith(mousePoint))
                activeScreen = s;
        }

        if (activeScreen == null)
            return;
        screenshot = new Bitmap(activeScreen.Bounds.Width, activeScreen.Bounds.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        graphics = Graphics.FromImage(screenshot);

        graphics.CopyFromScreen(
            activeScreen.Bounds.X,
            activeScreen.Bounds.Y,
            0,
            0,
            activeScreen.Bounds.Size,
            CopyPixelOperation.SourceCopy);

        screenshot.Save(@"C:\Users\David\Desktop\screen.png");
    }