WPF中使用winform控件picturebox,获取handle调用公司内部接口显示视频。
需求分两步,第一步:实现拍照功能;第二步:给别人提供接口将照片推送到页面中。
第一步实现:
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hwnd);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, int nWidth, int nHeight);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);
[DllImport("user32.dll")]
public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, UInt32 nFlags);
[DllImport("gdi32.dll")]
public static extern IntPtr DeleteObject(IntPtr hgdiobj);
[DllImport("gdi32.dll")]
public static extern int DeleteDC(IntPtr hdc);
//对客户视频拍照
public static Bitmap CutControlBitmap(IntPtr winCotPtr)
{
//1先获取控件的大小
IntPtr hscrdc = GetWindowDC(winCotPtr);
RECT rECT = new RECT();
GetWindowRect(winCotPtr, ref rECT);
IntPtr mapPtr = CreateCompatibleBitmap(hscrdc, rECT.Right - rECT.Left, rECT.Bottom - rECT.Top);
IntPtr hmemdc = CreateCompatibleDC(hscrdc);
SelectObject(hmemdc, mapPtr);
PrintWindow(winCotPtr, hmemdc, 0);
Bitmap bmp = Bitmap.FromHbitmap(mapPtr);
DeleteObject(mapPtr);
DeleteDC(hscrdc);
DeleteDC(hmemdc);
//bmp.Save("aabbcc.jpg");
return bmp;
}
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
第二步:http接口推送照片
多次尝试Response.OutputStream直接发送byte[]都以失败告终。改为以下方式:
Bitmap imgByte = imageHelper.CutControlBitmap(MainWindow.mainWindowsInstance.intPtrDest);
using (hlc.Response.OutputStream)
{
hlc.Response.Headers["Pragma"] = "no-cache";
hlc.Response.Headers["Cache-Control"] = "no-cache";
hlc.Response.ContentType = "image/Jpeg";
imgByte.Save(hlc.Response.OutputStream, ImageFormat.Jpeg);
hlc.Response.OutputStream.Flush();
if (GlobalInfo.logManager != null)
{
GlobalInfo.logManager.Info(callback + "({'ret':'CustomerPhotos'})");
}
}