2009-06-12 32 views
1

这是一个使用C#的Windows应用程序。我想用计时器捕捉屏幕截图。计时器设置为5000毫秒的时间间隔。随着计时器启动,应使用源窗口标题捕获桌面屏幕。如何用C#定时器捕获屏幕?

try 
{ 
    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); 
    timer.Tick += new EventHandler(timer2_Tick); 
    timer.Interval = (100) * (50); 
    timer.Enabled = true; 
    timer.Start(); 

    ScreenShots sc = new ScreenShots(); 
    sc.pictureBox1.Image = system_serveillance.CaptureScreen.GetDesktopImage(); 

    while(sc.pictureBox1.Image != null) 
    { 
     sc.pictureBox1.Image.Save("s"+".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); 
     sc.pictureBox1.Image = null; 
    } 

此代码无法正常工作。我怎样才能使它工作?

+0

“while”循环应该做什么? – 2009-06-12 12:18:34

+0

你能否更具体地说明“不能正常工作”的含义。 – ChrisF 2009-06-12 12:20:35

回答

6

由于你没有处理tick事件。皮特也指出你的文件将被覆盖在每个打勾上

它需要看起来更像下面的内容,这不是确切的代码,但它应该给你一个想法

private Int32 pictureCount = 0; 

    public Form1() 
    { 
     timer1.Tick += new EventHandler(this.timer1_Tick); 
     timer1.Interval = (100) * (50); 
     timer1.Enabled = true; 
     timer1.Start(); 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     /* Screen capture logic here */ 
     sc.pictureBox1.Image.Save(pictureCount.ToString() + ".jpg", ImageFormat.Jpeg); 
     pictureCount++; 
    } 
1

你已经开始了你的计时器,但你的屏幕保存程序似乎没有在你的计时器滴答代码中(除非你已经从帖子中省略了代码)。同样,你每次都会覆盖s.jpg,我认为这不是你想要的,在这里使用while子句也很奇怪,因为你只需要执行一个if测试

0

此外,你是在try中声明你的Timer - 所以如果你离开该范围,你的Timer将不再存在。就目前而言,您的代码将陷入困境,您的GUI将无法做其他事情。 (我认为)。

1

我认为我的开源BugTracker.NET应用程序附带的屏幕捕获实用程序具有您正在查找的功能或与其非常接近的功能。

请参阅http://ifdefined.com/blog/post/Screen-capture-utility-in-C-NET.aspx了解屏幕捕获实用程序的外观。延迟代码如下所示,主窗口首先隐藏自身,然后使用BeginInvoking本身来执行实际的延迟和捕获。下载BugTracker.NET,您将获得屏幕截图应用程序的完整源代码。

void buttonCapture_Click(object sender, Exception e) 
{ 
    this.Hide(); 
    BeginInvoke(new SimpleDelegate(CaptureForeground)); 
} 

     private void CaptureForeground() 
{ 
    // delay... 
    System.Threading.Thread.Sleep(500 + (1000 * (int)numericUpDownDelay.Value)); 

    // Get foreground window rect using native calls 
    IntPtr hWnd = GetForegroundWindow(); 
    RECT rct = new RECT(); 
    GetWindowRect(hWnd, ref rct); 

    Rectangle r = new Rectangle(); 
    r.Location = new Point(rct.Left, rct.Top); 
    r.Size = new Size(rct.Right - rct.Left, rct.Bottom - rct.Top); 
    CaptureBitmap(r); 

    this.Show(); 
} 

private void CaptureBitmap(Rectangle r) 
{ 
    bitmap = new Bitmap(r.Width, r.Height); 
    { 
     using (Graphics g = Graphics.FromImage(bitmap)) 
     { 
      g.CopyFromScreen(r.Location, new Point(0, 0), r.Size); 
     } 
    } 
}