Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am using Visual studio 2015 coded UI for automating my application. I want capture an window with mouse cursor on it. Could any one have or done this type of mouse cursor capture scenario.

Please help

Regards,
Ranjit

What I have tried:

Current I have tried many method using the in build functionality. But I was not able to capture mouse cursor.
Posted
Updated 8-May-17 0:51am
v2

1 solution

Here you go:

[StructLayout(LayoutKind.Sequential)]
struct CURSORINFO
{
    public Int32 cbSize;
    public Int32 flags;
    public IntPtr hCursor;
    public POINTAPI ptScreenPos;
}

[StructLayout(LayoutKind.Sequential)]
struct POINTAPI
{
    public int x;
    public int y;
}

[DllImport("user32.dll")]
static extern bool GetCursorInfo(out CURSORINFO pci);

[DllImport("user32.dll")]
static extern bool DrawIcon(IntPtr hDC, int X, int Y, IntPtr hIcon);

const Int32 CURSOR_SHOWING = 0x00000001;

public static Bitmap CaptureScreen(bool CaptureMouse)
{
    Bitmap result = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format24bppRgb);

    try
    {
        using (Graphics g = Graphics.FromImage(result))
        {
            g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);

            if (CaptureMouse)
            {
                CURSORINFO pci;
                pci.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(CURSORINFO));

                if (GetCursorInfo(out pci))
                {
                    if (pci.flags == CURSOR_SHOWING)
                    {
                        DrawIcon(g.GetHdc(), pci.ptScreenPos.x, pci.ptScreenPos.y, pci.hCursor);
                        g.ReleaseHdc();
                    }
                }
            }
        }
    }
    catch
    {
        result = null;
    }

    return result;
}
 
Share this answer
 
Comments
Member 13186404 8-May-17 6:53am    
Were do i get user32.dll??
Wessel Beulink 8-May-17 6:59am    
....add using System.Runtime.InteropServices;
Member 13186404 8-May-17 7:09am    
were does the image get saved?
Wessel Beulink 8-May-17 7:39am    
it returns a bitmap image as result call the function and do whatever you want to do with the bitmap. Save it in database or local storage.

use the .save function on the bitmap result.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);

fileName = path + name.
Or save it as blob in database

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900