Remove space left after console scrollbars in C# - c#

I'm making a console game in C# in Visual Studio and I want to make the game to be in the full console window.
I resized the buffer and window to be the same size, but it looks like the space after the scrollbars remained, which will probably be really annoying to look at. I wonder if there's any way to remove that blank space in C#, or at least add grayed-out scrollbars. I saw a similar thread, but it was in C++.
Here's a reproducible example:
using Microsoft.Win32.SafeHandles;
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace ConsoleTest1
{
class Program
{
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern SafeFileHandle CreateFile(
string fileName,
[MarshalAs(UnmanagedType.U4)] uint fileAccess,
[MarshalAs(UnmanagedType.U4)] uint fileShare,
IntPtr securityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
[MarshalAs(UnmanagedType.U4)] int flags,
IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteConsoleOutput(
SafeFileHandle hConsoleOutput,
CharInfo[] lpBuffer,
Coord dwBufferSize,
Coord dwBufferCoord,
ref SmallRect lpWriteRegion);
[StructLayout(LayoutKind.Sequential)]
public struct Coord
{
public short X, Y;
public Coord(short x, short y)
{
X = x;
Y = y;
}
}
[StructLayout(LayoutKind.Explicit)]
public struct CharUnion
{
[FieldOffset(0)] public char UnicodeChar;
[FieldOffset(0)] public byte AsciiChar;
}
[StructLayout(LayoutKind.Explicit)]
public struct CharInfo
{
[FieldOffset(0)] public CharUnion Char;
[FieldOffset(2)] public short Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct SmallRect
{
public short Left, Top, Right, Bottom;
public SmallRect(short width, short height)
{
Left = Top = 0;
Right = width;
Bottom = height;
}
}
[STAThread]
static void Main(string[] args)
{
short width = 50, height = 20;
SafeFileHandle handle = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
CharInfo[] buffer = new CharInfo[width * height];
SmallRect writeRegion = new SmallRect(width, height);
Console.SetWindowSize(width, height);
Console.SetBufferSize(width, height);
for (int i = 0; i < buffer.Length; ++i)
{
buffer[i].Attributes = 0xb0;
buffer[i].Char.UnicodeChar = ' ';
}
WriteConsoleOutput(handle, buffer, new Coord(width, height), new Coord(0, 0), ref writeRegion);
Console.ReadKey();
}
}
}
I don't really know how to do this or even if it's possible to remove the black space in this language.

Finally, after a lot of head-scratching, I think I've solved this issue. Firstly, I had to add some additional WinAPI methods:
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetConsoleScreenBufferInfoEx(
IntPtr hConsoleOutput,
ref ConsoleScreenBufferInfoEx ConsoleScreenBufferInfo);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleScreenBufferInfoEx(
IntPtr hConsoleOutput,
ref ConsoleScreenBufferInfoEx ConsoleScreenBufferInfoEx);
and structs:
[StructLayout(LayoutKind.Sequential)]
private struct ConsoleScreenBufferInfoEx
{
public uint cbSize;
public Coord dwSize;
public Coord dwCursorPosition;
public short wAttributes;
public SmallRect srWindow;
public Coord dwMaximumWindowSize;
public ushort wPopupAttributes;
public bool bFullscreenSupported;
public Colorref black, darkBlue, darkGreen, darkCyan, darkRed, darkMagenta, darkYellow, gray, darkGray, blue, green, cyan, red, magenta, yellow, white;
}
[StructLayout(LayoutKind.Sequential)]
private struct Colorref
{
public uint ColorDWORD;
}
After that, it was time to modify the part where the buffer and window were resized:
Console.SetWindowSize(width - 2, height);
Console.SetBufferSize(width, height);
IntPtr stdHandle = GetStdHandle(-11);
ConsoleScreenBufferInfoEx bufferInfo = new ConsoleScreenBufferInfoEx();
bufferInfo.cbSize = (uint)Marshal.SizeOf(bufferInfo);
GetConsoleScreenBufferInfoEx(stdHandle, ref bufferInfo);
++bufferInfo.srWindow.Right;
++bufferInfo.srWindow.Bottom;
SetConsoleScreenBufferInfoEx(stdHandle, ref bufferInfo);
And that's it! No more ugly black space (at least on my computer, haven't tested it on other Windows versions).

Related

WriteConsoleOutput() from Kernel32 not displaying text

I'm currently writing a small utility library to help improve performance when writing to the console, and I'm facing an issue where it fails to actually output any text. Below is my code:
public static class QuickDraw
{
private static short Width => (short)Console.WindowWidth;
private static short Height => (short)Console.WindowHeight;
private static SafeFileHandle Handle =>
Kernel32.CreateFile("$CONOUT", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);
private static Kernel32.Coord Cursor =>
new Kernel32.Coord((short)Console.CursorLeft, (short)Console.CursorTop);
private static Kernel32.SmallRect WriteRegion =>
new Kernel32.SmallRect() { Left = 0, Top = 0, Right = Width, Bottom = Height };
private static Kernel32.Coord BufferSize =>
new Kernel32.Coord(Width, Height);
private static Kernel32.Coord BufferCoord =>
new Kernel32.Coord(0, 0);
public static void Write(char[] text, ConsoleColor fg, ConsoleColor bg)
{
Kernel32.CharInfo[] buffer = new Kernel32.CharInfo[Width * Height];
Kernel32.Coord cursor = Cursor;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '\n')
{
cursor.X = 0;
cursor.Y++;
}
else
{
int index = (cursor.Y * Width) + cursor.X;
// Set character
buffer[index].Char.AsciiChar = (byte)text[i];
// Set color
// (Crazy heckin bitwise crap, don't touch.)
buffer[index].Attributes = (short)((int)fg | ((int)bg | (2 << 4)));
// Increment cursor
cursor.X++;
}
// Make sure that cursor does not exceed bounds of window
if (cursor.X >= Width)
{
cursor.X = 0;
cursor.Y++;
}
if (cursor.Y >= Height)
{
cursor.Y = 0;
}
}
var writeRegion = WriteRegion;
Kernel32.WriteConsoleOutput(Handle, buffer, BufferSize, BufferCoord, ref writeRegion);
Console.SetCursorPosition(cursor.X, cursor.Y);
}
}
// Taken from https://stackoverflow.com/a/2754674/7937949
internal static class Kernel32
{
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern SafeFileHandle CreateFile(
string fileName,
[MarshalAs(UnmanagedType.U4)] uint fileAccess,
[MarshalAs(UnmanagedType.U4)] uint fileShare,
IntPtr securityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
[MarshalAs(UnmanagedType.U4)] int flags,
IntPtr template);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern bool WriteConsoleOutput(
SafeFileHandle hConsoleOutput,
CharInfo[] lpBuffer,
Coord dwBufferSize,
Coord dwBufferCoord,
ref SmallRect lpWriteRegion);
[StructLayout(LayoutKind.Sequential)]
public struct Coord
{
public short X;
public short Y;
public Coord(short x, short y)
{
X = x;
Y = y;
}
}
[StructLayout(LayoutKind.Explicit)]
public struct CharUnion
{
[FieldOffset(0)] public char UnicodeChar;
[FieldOffset(0)] public byte AsciiChar;
}
[StructLayout(LayoutKind.Explicit)]
public struct CharInfo
{
[FieldOffset(2)] public CharUnion Char;
[FieldOffset(2)] public short Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct SmallRect
{
public short Left;
public short Top;
public short Right;
public short Bottom;
}
}
I've mostly taken the implementation from this post, adding a new class to simplify its use. I'm not entirely sure where my issue is, as my debugger is not working right, but I'm pretty sure it's in my implementation in QuickDraw.
When I try to use QuickDraw.Write(), the cursor moves to the end of whatever string it was trying to print, but nothing actually shows up. What am I doing wrong?
First of all, you didn't copy the code right. There are some mistakes.
in CharInfo change
[FieldOffset(2)] public CharUnion Char;
to
[FieldOffset(0)] public CharUnion Char;
Change $CONOUT to this CONOUT$
First set the Attribute and then the AsciiChar
And of course, if you want the correct foreground-/background color representation then you have to delete the 2 << 4. I don't even know why you put it there.

Retrieve color of windows 10 taskbar

I found out, that there is a static property in the System.Windows.SystemParameters class that declares the color the user chose for his Windows overall.
But there is a second possibility for the user that enables him to enable or disable, whether the taskbar/windows bar should use that same color.
I was unable to find a key for that in the SystemParameters-class.
I believe there is a registry value to find the colour and it is probably inside:
HKEY_CURRENT_USER\Control Panel\Colors
However on my system I have colours on the taskbar disabled and that colour value doesn't seem to appear in this key.
A work around would be to combine the answers to the following two questions:
TaskBar Location
How to Read the Colour of a Screen Pixel
You need the following imports:
[DllImport("shell32.dll")]
private static extern IntPtr SHAppBarMessage(int msg, ref APPBARDATA data);
[DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
private static extern int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
The following structs:
private struct APPBARDATA
{
public int cbSize;
public IntPtr hWnd;
public int uCallbackMessage;
public int uEdge;
public RECT rc;
public IntPtr lParam;
}
private struct RECT
{
public int left, top, right, bottom;
}
And the following constant:
private const int ABM_GETTASKBARPOS = 5;
Then you can call the following two methods:
public static Rectangle GetTaskbarPosition()
{
APPBARDATA data = new APPBARDATA();
data.cbSize = Marshal.SizeOf(data);
IntPtr retval = SHAppBarMessage(ABM_GETTASKBARPOS, ref data);
if (retval == IntPtr.Zero)
{
throw new Win32Exception("Please re-install Windows");
}
return new Rectangle(data.rc.left, data.rc.top, data.rc.right - data.rc.left, data.rc.bottom - data.rc.top);
}
public static Color GetColourAt(Point location)
{
using (Bitmap screenPixel = new Bitmap(1, 1, PixelFormat.Format32bppArgb))
using (Graphics gdest = Graphics.FromImage(screenPixel))
{
using (Graphics gsrc = Graphics.FromHwnd(IntPtr.Zero))
{
IntPtr hSrcDC = gsrc.GetHdc();
IntPtr hDC = gdest.GetHdc();
int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, location.X, location.Y, (int)CopyPixelOperation.SourceCopy);
gdest.ReleaseHdc();
gsrc.ReleaseHdc();
}
return screenPixel.GetPixel(0, 0);
}
}
Like this:
Color taskBarColour = GetColourAt(GetTaskbarPosition().Location);

GDI Write Bitmap to File in C#

I'm trying to Capture an Image from a window given the Handle/DC. I want to capture the Image with all the transparency and pixels so I decided I'd use GDI/GDI+.
The below code is what I have, but when it "writes" the bitmap, it writes it wrong :S In other words, the file is unreadable. It is blank. Yet it is 20kb in size :S
Any ideas what is wrong?
Imports.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace Imaging
{
static class Imports
{
public enum ObjectType : uint
{
OBJ_PEN = 1,
OBJ_BRUSH = 2,
OBJ_DC = 3,
OBJ_METADC = 4,
OBJ_PAL = 5,
OBJ_FONT = 6,
OBJ_BITMAP = 7,
OBJ_REGION = 8,
OBJ_METAFILE = 9,
OBJ_MEMDC = 10,
OBJ_EXTPEN = 11,
OBJ_ENHMETADC = 12,
OBJ_ENHMETAFILE = 13
}
public enum TernaryRasterOperations : uint
{
SRCCOPY = 0x00CC0020,
SRCPAINT = 0x00EE0086,
SRCAND = 0x008800C6,
SRCINVERT = 0x00660046,
SRCERASE = 0x00440328,
NOTSRCCOPY = 0x00330008,
NOTSRCERASE = 0x001100A6,
MERGECOPY = 0x00C000CA,
MERGEPAINT = 0x00BB0226,
PATCOPY = 0x00F00021,
PATPAINT = 0x00FB0A09,
PATINVERT = 0x005A0049,
DSTINVERT = 0x00550009,
BLACKNESS = 0x00000042,
WHITENESS = 0x00FF0062,
CAPTUREBLT = 0x40000000
}
[StructLayout(LayoutKind.Sequential)]
public struct Rect
{
public int Left, Top, Right, Bottom;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BITMAPFILEHEADER
{
public ushort bfType;
public uint bfSize;
public ushort bfReserved1;
public ushort bfReserved2;
public uint bfOffBits;
}
[StructLayout(LayoutKind.Sequential)]
public struct BITMAPINFOHEADER
{
public uint biSize;
public int biWidth;
public int biHeight;
public ushort biPlanes;
public ushort biBitCount;
public uint biCompression;
public uint biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public uint biClrUsed;
public uint biClrImportant;
public void Init()
{
biSize = (uint)Marshal.SizeOf(this);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct BITMAPINFO
{
public uint biSize;
public int biWidth;
public int biHeight;
public ushort biPlanes;
public ushort biBitCount;
public uint biCompression;
public uint biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public uint biClrUsed;
public uint biClrImportant;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public uint[] cols;
}
[StructLayout(LayoutKind.Sequential)]
public struct BITMAP
{
public int bmType;
public int bmWidth;
public int bmHeight;
public int bmWidthBytes;
public ushort bmPlanes;
public ushort bmBitsPixel;
public IntPtr bmBits;
};
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll")]
public static extern IntPtr GetDC(IntPtr WindowHandle);
[DllImport("user32.dll")]
public static extern void ReleaseDC(IntPtr WindowHandle, IntPtr DC);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr WindowHandle, ref Rect rect);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool PrintWindow(IntPtr hwnd, IntPtr DC, uint nFlags);
[DllImport("user32.dll")]
public static extern int SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
public static extern int GetWindowRgn(IntPtr hWnd, IntPtr hRgn);
[DllImport("gdi32.dll")]
public static extern IntPtr GetCurrentObject(IntPtr DC, ObjectType uObjectType);
[DllImport("gdi32.dll")]
public static extern int GetObject(IntPtr hObject, int nCount, ref BITMAP lpObject);
[DllImport("gdi32.dll", SetLastError = true)]
public static extern IntPtr CreateCompatibleDC(IntPtr DC);
[DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
public static extern bool DeleteDC(IntPtr DC);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr DC, int nWidth, int nHeight);
[DllImport("gdi32.dll", ExactSpelling = true, PreserveSig = true, SetLastError = true)]
public static extern IntPtr SelectObject(IntPtr DC, IntPtr hgdiobj);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);
[DllImport("gdi32.dll")]
static extern bool FillRgn(IntPtr DC, IntPtr hrgn, IntPtr hbr);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateSolidBrush(uint crColor);
[DllImport("gdi32.dll")]
public static extern int GetDIBits(IntPtr DC, IntPtr hbmp, uint uStartScan, uint cScanLines, [Out] byte[] lpvBits, ref BITMAPINFO lpbmi, uint uUsage);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool BitBlt(IntPtr DC, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr SrcDC, int nXSrc, int nYSrc, TernaryRasterOperations dwRop);
}
}
My PBitmap class:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace Imaging
{
class PBitmap
{
private Bitmap Img = null;
private Imports.BITMAPINFO Info;
private Imports.BITMAPFILEHEADER bFileHeader;
public PBitmap(IntPtr Window, int X, int Y, uint BitsPerPixel = 24)
{
IntPtr DC = Imports.GetDC(Window);
Imports.BITMAP Bmp = new Imports.BITMAP();
IntPtr hBmp = Imports.GetCurrentObject(DC, Imports.ObjectType.OBJ_BITMAP);
if (Imports.GetObject(hBmp, Marshal.SizeOf(Bmp), ref Bmp) == 0)
throw new Exception("ERROR_INVALID_WINDOW_HANDLE.");
Imports.Rect BMBox = new Imports.Rect();
Imports.GetWindowRect(Window, ref BMBox); //GetClientRect
int width = BMBox.Right - BMBox.Left;
int height = BMBox.Bottom - BMBox.Top;
IntPtr MemDC = Imports.GetDC(IntPtr.Zero);
IntPtr SDC = Imports.CreateCompatibleDC(MemDC);
IntPtr hSBmp = Imports.CreateCompatibleBitmap(MemDC, width, height);
Imports.DeleteObject(Imports.SelectObject(SDC, hSBmp));
Imports.BitBlt(SDC, 0, 0, width, height, DC, X, Y, Imports.TernaryRasterOperations.SRCCOPY);
long size = ((width * BitsPerPixel + 31) / 32) * 4 * height;
Info = new Imports.BITMAPINFO();
bFileHeader = new Imports.BITMAPFILEHEADER();
Info.biSize = (uint)Marshal.SizeOf(Info);
Info.biWidth = width;
Info.biHeight = height;
Info.biPlanes = 1;
Info.biBitCount = (ushort)BitsPerPixel;
Info.biCompression = 0;
Info.biSizeImage = (uint)size;
bFileHeader.bfType = 0x4D42;
bFileHeader.bfOffBits = (uint)(Marshal.SizeOf(bFileHeader) + Marshal.SizeOf(Info));
bFileHeader.bfSize = (uint)(bFileHeader.bfOffBits + size);
byte[] ImageData = new byte[size];
Imports.GetDIBits(SDC, hSBmp, 0, (uint)height, ImageData, ref Info, 0);
var bw = new BinaryWriter(File.Open("C:/Users/*******/Desktop/Foo.bmp", FileMode.OpenOrCreate));
bw.Write((short)0x4D42);
bw.Write((uint)(bFileHeader.bfOffBits + size));
bw.Write((uint)0);
bw.Write((uint)54);
bw.Write((uint)Info.biSize);
bw.Write(width);
bw.Write(height);
bw.Write((short)Info.biPlanes);
bw.Write(BitsPerPixel);
bw.Write((uint)0);
bw.Write((uint)size);
bw.Write((uint)0);
bw.Write((uint)0);
bw.Write((uint)0);
bw.Write((uint)0);
bw.Write(ImageData);
bw.Flush();
bw.Close();
bw.Dispose();
Imports.DeleteDC(SDC);
Imports.DeleteObject(hSBmp);
Imports.ReleaseDC(IntPtr.Zero, MemDC);
Imports.ReleaseDC(Window, DC);
}
}
}
If you're looking for a quick band-aid fix to get this done (it just needs to work, not used often, etc) consider just loading the image back into .NET and re-saving it with PNG compression enabled. The .NET framework will handle this for you and the file size will be a lot more optimal. Of course, if this is for a real-time application this isn't ideal.

WebBrowser.DrawToBitmap() or other methods?

I am trying to capture the content of the WebBrowser control. DrawToBitmap() would work perfectly, but it is not supported in documentation for the WebBrowser control. I have been trying to find another way to capture the contents of the WebBrowser control and save them to a local image file.
Does anyone have any workarounds or other methods to save the contents of the WebBrowser control to a local image file?
The Control.DrawToBitmap doesn't always work so I resorted to the following native API calls that provide more consistent results:
The Utilities class. Call Utilities.CaptureWindow(Control.Handle) to capture a specific control:
public static class Utilities
{
public static Image CaptureScreen()
{
return CaptureWindow(User32.GetDesktopWindow());
}
public static Image CaptureWindow(IntPtr handle)
{
IntPtr hdcSrc = User32.GetWindowDC(handle);
RECT windowRect = new RECT();
User32.GetWindowRect(handle, ref windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
IntPtr hdcDest = Gdi32.CreateCompatibleDC(hdcSrc);
IntPtr hBitmap = Gdi32.CreateCompatibleBitmap(hdcSrc, width, height);
IntPtr hOld = Gdi32.SelectObject(hdcDest, hBitmap);
Gdi32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, ApiConstants.SRCCOPY);
Gdi32.SelectObject(hdcDest, hOld);
Gdi32.DeleteDC(hdcDest);
User32.ReleaseDC(handle, hdcSrc);
Image image = Image.FromHbitmap(hBitmap);
Gdi32.DeleteObject(hBitmap);
return image;
}
}
The Gdi32 class:
public class Gdi32
{
[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop);
[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 bool DeleteDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
}
The User32 class:
public static class User32
{
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
[DllImport("user32.dll")]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
}
The constants used:
public const int SRCCOPY = 13369376;
The structs used:
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
A friendly Control extension method:
public static class ControlExtensions
{
public static Image DrawToImage(this Control control)
{
return Utilities.CaptureWindow(control.Handle);
}
}
This is a code snippet from my CC.Utilities project and I specifically wrote it to take screenshots from the WebBrowser control.
The following method can capture the entire window image even if the window is larger than the size of screen. Then it can capture the image of the contents of the page if the window be resized to the webBrowser.Document.OffsetRectangle.Size
class NativeMethods
{
[ComImport]
[Guid("0000010D-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IViewObject
{
void Draw([MarshalAs(UnmanagedType.U4)] uint dwAspect, int lindex, IntPtr pvAspect, [In] IntPtr ptd, IntPtr hdcTargetDev, IntPtr hdcDraw, [MarshalAs(UnmanagedType.Struct)] ref RECT lprcBounds, [In] IntPtr lprcWBounds, IntPtr pfnContinue, [MarshalAs(UnmanagedType.U4)] uint dwContinue);
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
public static void GetImage(object obj, Image destination, Color backgroundColor)
{
using(Graphics graphics = Graphics.FromImage(destination))
{
IntPtr deviceContextHandle = IntPtr.Zero;
RECT rectangle = new RECT();
rectangle.Right = destination.Width;
rectangle.Bottom = destination.Height;
graphics.Clear(backgroundColor);
try
{
deviceContextHandle = graphics.GetHdc();
IViewObject viewObject = obj as IViewObject;
viewObject.Draw(1, -1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, deviceContextHandle, ref rectangle, IntPtr.Zero, IntPtr.Zero, 0);
}
finally
{
if(deviceContextHandle != IntPtr.Zero)
{
graphics.ReleaseHdc(deviceContextHandle);
}
}
}
}
}
Usage :
Bitmap screenshot = new Bitmap(1024, 768);
NativeMethods.GetImage(webBrowser.ActiveXInstance, screenshot, Color.White);
I am using DrawToBitmap (Visual Studio 2008 C#) to capture big images (user signed invoices,content out of the screen). Basically it is working well but I am getting blank images. About 100 employees are using this software, about every 2 weeks I can see one blank image.
I have done a lot of testing and one funny thing I found is:
I created a button to generate the image from the webbrowser. Usually is OK but if I click the webbrowser first, then click the create-button, the blank image will appear.
I used OleDraw method as in this topic on SO, but integrated it in a class derived from WebBrowser. This allows to do normal Control.DrawToBitmap not only for the WebBrowser, but for a form with WebBrowser in it as well. This also works if the form is hidden (covered by another form, including MDI parent form) and should work when user has locked session with Win+L (I haven't tested it).
public class WebBrowserEx : WebBrowser
{
private const uint DVASPECT_CONTENT = 1;
[DllImport("ole32.dll", PreserveSig = false)]
private static extern void OleDraw([MarshalAs(UnmanagedType.IUnknown)] object pUnk,
uint dwAspect,
IntPtr hdcDraw,
[In] ref System.Drawing.Rectangle lprcBounds
);
protected override void WndProc(ref Message m)
{
const int WM_PRINT = 0x0317;
switch (m.Msg)
{
case WM_PRINT:
Rectangle browserRect = new Rectangle(0, 0, this.Width, this.Height);
// Don't know why, but drawing with OleDraw directly on HDC from m.WParam.
// results in badly scaled (stretched) image of the browser.
// So, drawing to an intermediate bitmap first.
using (Bitmap browserBitmap = new Bitmap(browserRect.Width, browserRect.Height))
{
using (var graphics = Graphics.FromImage(browserBitmap))
{
var hdc = graphics.GetHdc();
OleDraw(this.ActiveXInstance, DVASPECT_CONTENT, hdc, ref browserRect);
graphics.ReleaseHdc(hdc);
}
using (var graphics = Graphics.FromHdc(m.WParam))
{
graphics.DrawImage(browserBitmap, Point.Empty);
}
}
// ignore default WndProc
return;
}
base.WndProc(ref m);
}
}

Multiple webcam capture in one avi with c# (windows forms)

I need to find a way how to make one video file from 2 or more webcam in C# (windows app). I tried to use the google for finding some samples, but no success. I found a way how to record a video from the webcam (with directshowNet, directx I can save two avi with two webcam...)
more about directShowNet:
http: //directshownet.sourceforge.net/
Sample for capturing video:
http: //www.codeproject.com/KB/directx/directshownet.aspx
For a simple example I have 2 webcams. I need to get the frames during the record, paste one frame near the other (make one image, create one frame from the two), and insert these new frames into a new avi.
Any idea? Is it possible to get the frames in time, and create one new avi from the 2 captured?
The question is bit old(!) but just in case: I have successfully used AForge.NET library. In its 2.1.4 version it has a sample that displays video from two cameras.
All you have to do is instead of using default Video Player control use VideoCaptureDevice and in NewFrame events create your desired bitmap.
AForge.NET even have a AVIWriter that you can use for creating output videos.
here this code for merge 2 images
#region TakeSnap Class
IntPtr memDc;
[StructLayout(LayoutKind.Sequential)]
public struct Sizes
{
public Int32 cx;
public Int32 cy;
public Sizes(Int32 x, Int32 y)
{
cx = x;
cy = y;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct BLENDFUNCTION
{
public byte BlendOp;
public byte BlendFlags;
public byte SourceConstantAlpha;
public byte AlphaFormat;
}
[StructLayout(LayoutKind.Sequential)]
public struct Points
{
public Int32 x;
public Int32 y;
public Points(Int32 x, Int32 y)
{
this.x = x;
this.y = y;
}
}
[DllImport("gdi32.dll",EntryPoint="DeleteDC")]
public static extern IntPtr DeleteDC(IntPtr hDc);
[DllImport("gdi32.dll",EntryPoint="DeleteObject")]
public static extern IntPtr DeleteObject(IntPtr hDc);
[DllImport("gdi32.dll",EntryPoint="BitBlt")]
public static extern bool BitBlt(IntPtr hdcDest,int xDest,
int yDest,int wDest,int hDest,IntPtr hdcSource,
int xSrc,int ySrc,int RasterOp);
[DllImport ("gdi32.dll",EntryPoint="CreateCompatibleBitmap")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc,
int nWidth, int nHeight);
[DllImport ("gdi32.dll",EntryPoint="CreateCompatibleDC")]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport ("gdi32.dll",EntryPoint="SelectObject")]
public static extern IntPtr SelectObject(IntPtr hdc,IntPtr bmp);
[DllImport("user32.dll", EntryPoint="GetDesktopWindow")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll",EntryPoint="GetDC")]
public static extern IntPtr GetDC(IntPtr ptr);
[DllImport("user32.dll",EntryPoint="GetSystemMetrics")]
public static extern int GetSystemMetrics(int abc);
[DllImport("user32.dll",EntryPoint="GetWindowDC")]
public static extern IntPtr GetWindowDC(Int32 ptr);
[DllImport("user32.dll",EntryPoint="ReleaseDC")]
public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDc);
protected static IntPtr m_HBitmap;
public const int SM_CXSCREEN=0;
public const int SM_CYSCREEN=1;
public const int SRCCOPY = 13369376;
#endregion
private IntPtr get_pointer(string path)
{
Bitmap bitmap=new Bitmap(path);
IntPtr oldBits = IntPtr.Zero;
IntPtr screenDC = GetDC(IntPtr.Zero);
IntPtr hBitmap = IntPtr.Zero;
memDc = CreateCompatibleDC(screenDC);
try
{
Point topLoc = new Point(Left, Top);
Sizes bitMapSize = new Sizes(bitmap.Width, bitmap.Height);
BLENDFUNCTION blendFunc = new BLENDFUNCTION();
Points srcLoc = new Points(0, 0);
hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
IntPtr pt= SelectObject(memDc, hBitmap);
ReleaseDC(IntPtr.Zero, screenDC);
return memDc;
}
catch(Exception ex)
{
return this.Handle;
}
}
public Bitmap GetDesktopImage()
{
try
{
Sizes size;
IntPtr hBitmap;
IntPtr hDC = get_pointer(#"C:\Documents and Settings\admin\Desktop\11_13_40_453.jpg");
IntPtr hMemDC = CreateCompatibleDC(hDC);
IntPtr hDC1 = get_pointer(#"C:\Documents and Settings\admin\Desktop\11_13_42_906.jpg");
size.cx = this.Width-2;
size.cy = this.Height-22;
hBitmap = CreateCompatibleBitmap(hDC, size.cx*2, size.cy);
if (hBitmap!=IntPtr.Zero)
{
IntPtr hOld = (IntPtr)SelectObject(hMemDC, hBitmap);
BitBlt(hMemDC, 0, 0,size.cx,size.cy, hDC,0, 0,SRCCOPY);
BitBlt(hMemDC, size.cx, 0,size.cx,size.cy, hDC1,0, 0,SRCCOPY);
SelectObject(hMemDC, hOld);
DeleteDC(hMemDC);
DeleteDC(memDc);
ReleaseDC(this.Handle, hDC);
ReleaseDC(this.Handle, hDC1);
Bitmap bmp = System.Drawing.Image.FromHbitmap(hBitmap);
DeleteObject(hBitmap);
GC.Collect();
return bmp;
}
return null;
}
catch(Exception ex)
{
return null;
}
}
private void Createimage()
{
try
{
Bitmap bm= GetDesktopImage();
bm.Save(Application.StartupPath+"\\temp\\"+DateTime.Now.ToString("hh-mm-ss ff")+".Jpeg",System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Categories

Resources