C# Clipboard problem

G

Guest

Hello,
I'm having a strange clipboard problem. In my code, I send Alt+Print Screen
to the current window and save the image to disk. The code is pasted below:

public string CaptureAndSave()
{
SendKeys.Send("%{PRTSC}");
//Clipboard.SetText("0");
//Clipboard.Clear();
//MessageBox.Show("here");
if (Clipboard.ContainsImage())
{
//get image
Image image = (Bitmap)Clipboard.GetImage();

//prep file name
string s = Path.GetFileName(Path.GetTempFileName());
string fileName =
Path.Combine(Directory.GetCurrentDirectory(),
Path.ChangeExtension(s, ".emf"));

//save image
image.Save(fileName, System.Drawing.Imaging.ImageFormat.Emf);
}
else
MessageBox.Show("no image!");

The behavior of the program, unexpectedly, depends on the current state of
the clipboard. If the clipboard is empty, or if it contains text,
"Clipboard.ContainsImage()" will return false. If the clipboard happens to
contain an image, it will save that one instead. This is strange because if I
open mspaint and click Edit->Paste, it will paste the correct image. I
thought, perharps, the SendKeys function needed more time than I was giving
it but the behavior is the same even if I use Thread.Sleep or FOR loops. The
only configuration that worked (as expected) was when I displayed a message
box after sending the keys. Does anyone have any idea why the program behaves
this way? I'm using VS 2005 beta2 with .NET Framework v2.0. I do not have a
release version of VS.NET installed to test whether this is a problem related
to my beta 2 version of VS.

Thanks in advance,
Jose
 
G

Guest

It appears that using SendKeys.SendWait, instead of SendKeys.Send, fixes the
problem. Still, many examples from programming forums use SendKeys.Send. Why
does it work for them?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top