Is there any reason why the following code should crash the current windows form it's operating in? It works if I take the screenshot quickly, but if I leave the windows up for a few seconds my windows form gets a little hour glass in front of it and wont respond to anything, then I ussually have to kill it the program the hard way.
private
void ActiveWindowCaptureAlert(){
MessageBox.Show("Select the window you want a screenshot of, then press capture!"); while (this.Handle == GetForegroundWindow()){
Thread.Sleep(10); //sleeping for even 100 seems to make the loop crash}
while (this.Handle != GetForegroundWindow()){
hOld = GetForegroundWindow();
Thread.Sleep(10);}
// ActiveWindowCapture();}
hOld is a windows handle, as you may have guessed...
AlanPosted Nov 28, 2007, 3:15 PM
It sounds to me as though the combination of Thread.Sleep and GetForegroundWindow may be producing a deadlock.
Rather than using Thread.Sleep, I'd try an old fashioned way of producing a delay, a 'do nothing' for loop.
On my (slow) home machine the following line produces a delay of around 100 milliseconds:
for(int i = 0; i < 40000000 ; i++);
Another possibility would be to use an event - Deactivate or LostFocus - to tell you when the current form has lost the focus.
Adam TurnerPosted Nov 28, 2007, 1:12 PM
Actually, it progresses through the loops. Otherwise it would never call the function to create the screenshot. But the thing is it only seems to work if it's done under a few seconds, otherwise it crashes.
But if what you're saying is true, why is it true, and why does it appear to go through the loop to the intended function? I guess I'm just daft (and new to C#/windows programming), but I'm not seeing it.
Alan C BalkanyPosted Nov 28, 2007, 10:06 AM