屏幕截图程序加载了RAM

时间:2018-09-18 11:08:06

标签: c#

所以我对C#来说还比较陌生,我想开发一个应用程序,向您显示您悬停的像素的颜色,但是使用此代码似乎是个大问题。 非常感谢您的帮助 代码:

private void timer1_Tick(object sender, EventArgs e)
{
    b = null;
    b = Screenshot();
    Color color = b.GetPixel(Cursor.Position.X, Cursor.Position.Y);
    label1.Text = color.Name;
    label2.Text = Cursor.Position.Y.ToString() + Cursor.Position.X.ToString();
}

private Bitmap Screenshot()
{
    Bitmap Screen = new Bitmap(SystemInformation.VirtualScreen.Width,SystemInformation.VirtualScreen.Height);
    Graphics g = Graphics.FromImage(Screen);
    g.CopyFromScreen(SystemInformation.VirtualScreen.X,SystemInformation.VirtualScreen.Y, 0, 0, Screen.Size);
    return Screen;
}

2 个答案:

答案 0 :(得分:2)

您既不需要计时器也不需要复制整个屏幕。只需添加一个MouseMove处理程序,如下所示:

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    using (var bitmap = new Bitmap(1, 1))
    {
        var graphics = Graphics.FromImage(bitmap);
        var position = PointToScreen(e.Location);
        graphics.CopyFromScreen(position.X, position.Y, 0, 0, new Size(1, 1));
        var color = bitmap.GetPixel(0, 0);

        label1.Text = color.ToString();
    }
}

或重新使用位图:

private readonly Bitmap bitmap = new Bitmap(1, 1);

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    var graphics = Graphics.FromImage(bitmap);
    var position = PointToScreen(e.Location);
    graphics.CopyFromScreen(position.X, position.Y, 0, 0, new Size(1, 1));
    var color = bitmap.GetPixel(0, 0);

    label1.Text = color.ToString();
}

答案 1 :(得分:0)

以正确的方式使用代码时,您的代码可以完美运行:(无全局'b')

private void Timer1_Tick(object sender, EventArgs e)
{
  using (var b = Screenshot())
  {
    label1.Text = b.GetPixel(Cursor.Position.X, Cursor.Position.Y).Name;
    label2.Text = Cursor.Position.ToString();
  }
}

private static Bitmap Screenshot()
{
  var Screen = new Bitmap(SystemInformation.VirtualScreen.Width, SystemInformation.VirtualScreen.Height);
  var g = Graphics.FromImage(Screen);
  g.CopyFromScreen(SystemInformation.VirtualScreen.X, SystemInformation.VirtualScreen.Y, 0, 0, Screen.Size);
  return Screen;
}

但是,当然,尝试仅复制单个像素的整个屏幕是错误的。...

因此,请使用类似Clemens的固定代码。

例如:

private readonly Bitmap screen = new Bitmap(1, 1);
private static readonly Size size = new Size(1, 1);

private void Timer1_Tick(object sender, EventArgs e)
{
  using (var g = Graphics.FromImage(screen))
  {
    g.CopyFromScreen(Cursor.Position.X, Cursor.Position.Y, 0, 0, size);

    label1.Text = screen.GetPixel(0, 0).Name;
    label2.Text = Cursor.Position.ToString();
  }
}

也不要忘记以Dispose方法的形式处理位图。