2

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.

Rohit
  • 18,575
  • 3
  • 11
  • 9
  • Related : http://stackoverflow.com/questions/24466482/how-to-take-a-screenshot-of-a-wpf-control –  Jul 02 '16 at 12:14
  • You don't need to above code . use `RenderTargetBitmap` to get window as image . – Maria Jul 02 '16 at 15:47
  • 1
    Do you only want to capture wpf content (whatever is your root control in the window) or also the window itself including its frame title and top right buttons? – Ronan Thibaudau Jul 02 '16 at 16:07

1 Answers1

4

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);
Sagar
  • 470
  • 1
  • 6
  • 13