Reputation: 19165
I have WPF application in which we wanted to achieve functionality of screenshot using code behind.
Whenever we want we should be able take screenshot of our application on user's machine (not entire print-screen)
For this I done some google and found that DllImport("user32.dll")
will help me in this regards. However, I don't have any clue how to use this? Which method I should refer here?
I tried with below code but no luck-
[DllImport("User32.dll")]
public static extern int SetForegroundWindow(IntPtr point);
Process p = Process.GetCurrentProcess();
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
IntPtr processFoundWindow = p.MainWindowHandle;
Please suggest.
Upvotes: 2
Views: 3241
Reputation: 490
This is how I have used in my application earlier.
I created class to handle screenshot functionality.
public sealed class snapshotHandler
{
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int m_left;
public int m_top;
public int m_right;
public int m_bottom;
}
[DllImport("user32.dll")]
private static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
public static void Savesnapshot(IntPtr handle_)
{
RECT windowRect = new RECT();
GetWindowRect(handle_, ref windowRect);
Int32 width = windowRect.m_right - windowRect.m_left;
Int32 height = windowRect.m_bottom - windowRect.m_top;
Point topLeft = new Point(windowRect.m_left, windowRect.m_top);
Bitmap b = new Bitmap(width, height);
Graphics g = Graphics.FromImage(b);
g.CopyFromScreen(topLeft, new Point(0, 0), new Size(width, height));
b.Save(SNAPSHOT_FILENAME, ImageFormat.Jpeg);
}
}
To use above functionality, I am calling SaveSnapshot method.
SnapshotHandler.SaveSnapshot(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle);
Upvotes: 4