Taking screenshot with Win32 API (C# pInvoke) not working in IIS
- by Dillen Meijboom
I want to take a screenshot of an external website.
Currently my workflow is to start a Firefox instance with the specified URL and take a screenshot using PrintWindow in the Win32 API
When I run this application in IISExpress it works fine but when I run the same application in IIS on a windows VPS it is not working (screenshot is blank).
I don't know what I'm doing wrong?
My code:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Web;
namespace WebTools.Web
{
public class RemoteScreenshot
{
public static Bitmap TakeScreenshot(Process process)
{
// may need a process Refresh before
return TakeScreenshot(process.MainWindowHandle);
}
public static Bitmap TakeScreenshot(IntPtr handle)
{
RECT rc = new RECT();
GetWindowRect(handle, ref rc);
Bitmap bitmap = new Bitmap(rc.right - rc.left, rc.bottom - rc.top);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
PrintWindow(handle, graphics.GetHdc(), 0);
}
return bitmap;
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect);
[DllImport("user32.dll")]
private static extern bool PrintWindow(IntPtr hWnd, IntPtr hDC, int flags);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
public static void Save(string url, string file, int timeout = 0)
{
Process.Start(new ProcessStartInfo("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe", url)
{
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Maximized
});
Thread.Sleep(timeout);
var bitmap = TakeScreenshot(Process.GetProcessesByName("firefox").First());
bitmap.Save(file, ImageFormat.Png);
bitmap.Dispose();
Process.GetProcessesByName("firefox").First().Kill();
}
}
}
EDIT: Running Firefox works fine because the AppPool is under another account that has the rights to execute firefox.