Archive for Agosto 15th, 2008

Safely fire an event

CodeKeep C# Feed Agosto 15th, 2008

Description: Ensures that an event can be fired even if there are no subscribers. Also avoids concurrency issues involved with checking the event for null before firing it.

Link: http://www.codekeep.net/snippets/33ea188d-02c2-4335-b32a-f9b5c0d74a08.aspx

        /// <summary>
        /// Fires when the monitors status changes.
        /// </summary>
        public event MonitorStatusEventHandler MonitorStatusChanged = delegate { };

Convert Image to Byte Array

CodeKeep C# Feed Agosto 15th, 2008

Description: Convert an image object to a byte array in a specified format.

Link: http://www.codekeep.net/snippets/4541423e-c798-4876-b1f3-eb0533190c08.aspx

        /// <summary>
        /// Converts a System.Drawing.Image to a 1-dimensional byte array.
        /// </summary>
        /// <param name="imageToConvert">Image to convert</param>
        /// <param name="formatOfImage">Image format</param>
        /// <returns>Byte array representation of image</returns>
        private byte[] ConvertImageToByteArray(System.Drawing.Image imageToConvert, ImageFormat formatOfImage)
        {
            try
            {
                byte[] Ret;

                using (MemoryStream ms = new MemoryStream())
                {
                    imageToConvert.Save(ms, formatOfImage);
                    Ret = ms.ToArray();
                }
                return Ret;
            }
            catch (Exception ex) 
            {
      		//handle exception
                return new byte[0]; 
            }
        }

Take a screenshot of an open window

CodeKeep C# Feed Agosto 15th, 2008

Description: Given a handle of an open window, takes a screenshot of that window and returns it as an image object.

Link: http://www.codekeep.net/snippets/eaadd394-5088-47e4-8f4d-9354fe61a455.aspx

        /// <summary>
        /// Takes a screenshot of a specified window and keeps the result in the clipboard.
        /// </summary>
        /// <param name="hwnd">Window handle</param>
        private System.Drawing.Image GetScreenshot(int hwnd)
        {
            SetWindowPos((IntPtr)hwnd, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);

            //?? it works but why?
            Thread.Sleep(100);

            SetForegroundWindow((IntPtr)hwnd);

            uint intReturn = 0;
            INPUT structInput;
            structInput = new INPUT();
            structInput.type = (uint)1;
            structInput.ki.wScan = 0;
            structInput.ki.time = 0;
            structInput.ki.dwFlags = 0;
            structInput.ki.dwExtraInfo = 0;

            //Key down Alt Key
            structInput.ki.wVk = (ushort)VK.MENU;
            intReturn = SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));

            //Key down Print Screen
            structInput.ki.wVk = (ushort)VK.SNAPSHOT;//vk;
            intReturn = SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));

            //Key up Print Screen
            structInput.ki.dwFlags = KEYEVENTF_KEYUP;
            structInput.ki.wVk = (ushort)VK.SNAPSHOT;//vk;
            intReturn = SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));

            //Key up Alt
            structInput.ki.dwFlags = KEYEVENTF_KEYUP;
            structInput.ki.wVk = (ushort)VK.MENU;
            intReturn = SendInput((uint)1, ref structInput, Marshal.SizeOf(structInput));

            //Need to let the print screen copy catch up with the rest of the code, other wise the clipboard will be read before
            //it is written to
            Thread.Sleep(100);

            Win32.SetWindowPos((IntPtr)hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, Win32.TOPMOST_FLAGS);

            System.Windows.Forms.IDataObject data = Clipboard.GetDataObject();

            try
            {
                if (data.GetDataPresent(DataFormats.Bitmap))
                {
                    System.Drawing.Image image = (System.Drawing.Image)data.GetData(DataFormats.Bitmap, true);
                    return image;
                }
                else throw new Exception("Expected bitmap image.");
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        // For Windows Mobile, replace user32.dll with coredll.dll
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X,
           int Y, int cx, int cy, uint uFlags);

        public const ushort KEYEVENTF_KEYUP = 0x0002;

        public enum VK : ushort
        {
            SHIFT = 0x10,
            CONTROL = 0x11,
            MENU = 0x12,
            ESCAPE = 0x1B,
            BACK = 0x08,
            TAB = 0x09,
            RETURN = 0x0D,
            PRIOR = 0x21,
            NEXT = 0x22,
            END = 0x23,
            HOME = 0x24,
            LEFT = 0x25,
            UP = 0x26,
            RIGHT = 0x27,
            DOWN = 0x28,
            SELECT = 0x29,
            PRINT = 0x2A,
            EXECUTE = 0x2B,
            SNAPSHOT = 0x2C,
            INSERT = 0x2D,
            DELETE = 0x2E,
            HELP = 0x2F,
            NUMPAD0 = 0x60,
            NUMPAD1 = 0x61,
            NUMPAD2 = 0x62,
            NUMPAD3 = 0x63,
            NUMPAD4 = 0x64,
            NUMPAD5 = 0x65,
            NUMPAD6 = 0x66,
            NUMPAD7 = 0x67,
            NUMPAD8 = 0x68,
            NUMPAD9 = 0x69,
            MULTIPLY = 0x6A,
            ADD = 0x6B,
            SEPARATOR = 0x6C,
            SUBTRACT = 0x6D,
            DECIMAL = 0x6E,
            DIVIDE = 0x6F,
            F1 = 0x70,
            F2 = 0x71,
            F3 = 0x72,
            F4 = 0x73,
            F5 = 0x74,
            F6 = 0x75,
            F7 = 0x76,
            F8 = 0x77,
            F9 = 0x78,
            F10 = 0x79,
            F11 = 0x7A,
            F12 = 0x7B,
            OEM_1 = 0xBA,   // ',:' for US
            OEM_PLUS = 0xBB,   // '+' any country
            OEM_COMMA = 0xBC,   // ',' any country
            OEM_MINUS = 0xBD,   // '-' any country
            OEM_PERIOD = 0xBE,   // '.' any country
            OEM_2 = 0xBF,   // '/?' for US
            OEM_3 = 0xC0,   // '`~' for US
            MEDIA_NEXT_TRACK = 0xB0,
            MEDIA_PREV_TRACK = 0xB1,
            MEDIA_STOP = 0xB2,
            MEDIA_PLAY_PAUSE = 0xB3,
            LWIN = 0x5B,
            RWIN = 0x5C
        }

        public struct KEYBDINPUT
        {
            public ushort wVk;
            public ushort wScan;
            public uint dwFlags;
            public long time;
            public uint dwExtraInfo;
        };

        [StructLayout(LayoutKind.Explicit, Size = 28)]
        public struct INPUT
        {
            [FieldOffset(0)]
            public uint type;
            [FieldOffset(4)]
            public KEYBDINPUT ki;
        };

        public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
        public static readonly IntPtr HWND_TOP = new IntPtr(0);
        public static readonly IntPtr HWND_BOTTOM = new IntPtr(1);

        // From winuser.h
        public const UInt32 SWP_NOSIZE = 0x0001;
        public const UInt32 SWP_NOMOVE = 0x0002;
        public const UInt32 SWP_NOZORDER = 0x0004;
        public const UInt32 SWP_NOREDRAW = 0x0008;
        public const UInt32 SWP_NOACTIVATE = 0x0010;
        public const UInt32 SWP_FRAMECHANGED = 0x0020;  /* The frame changed: send WM_NCCALCSIZE */
        public const UInt32 SWP_SHOWWINDOW = 0x0040;
        public const UInt32 SWP_HIDEWINDOW = 0x0080;
        public const UInt32 SWP_NOCOPYBITS = 0x0100;
        public const UInt32 SWP_NOOWNERZORDER = 0x0200;  /* Don't do owner Z ordering */
        public const UInt32 SWP_NOSENDCHANGING = 0x0400;  /* Don't send WM_WINDOWPOSCHANGING */

        public const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;

Get the title text of an open window

CodeKeep C# Feed Agosto 15th, 2008

Description: Given the handle of an open window, returns the text of the title.

Link: http://www.codekeep.net/snippets/47b10100-7003-40fa-9ff5-07b9ab9bee51.aspx

        /// <summary>
        /// Gets the title text of a window.
        /// </summary>
        /// <param name="hwnd">Window handle</param>
        /// <returns>Title text of window.</returns>
        private String GetWindowTitle(int hwnd)
        {
            int length = GetWindowTextLength((IntPtr)hwnd);
            StringBuilder windowTitle = new StringBuilder(length + 1);
            GetWindowText((IntPtr)hwnd, windowTitle, windowTitle.Capacity);
            return windowTitle.ToString();
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern int GetWindowTextLength(IntPtr hWnd);

Office OCR Component

CodeKeep C# Feed Agosto 15th, 2008

Description: Microsoft Office Document Imaging provides a method to perform OCR on a saved image file from code.

Link: http://www.codekeep.net/snippets/8785c6f3-d610-41d3-8dbb-363806385347.aspx

        /// <summary>
        /// Performs optical character recognition on an image file, and returns the text.
        /// </summary>
        /// <param name="fileName">Filename of image</param>
        /// <returns>Text of OCR</returns>
        private String ConvertImageToText(String fileName)
        {
            StringBuilder result = new StringBuilder();

            try
            {
                //Microsoft Office Document Imaging, used to OCR text on image
                MODI.Document modiDoc = new MODI.Document();

                modiDoc.Create(fileName);

                modiDoc.OCR(MiLANGUAGES.miLANG_ENGLISH, false, false);

                MODI.Image i = (MODI.Image)modiDoc.Images[0];

                foreach (MODI.Word w in i.Layout.Words)
                {
                    result.Append(w.Text);
                    result.Append(" ");
                }
            }
            catch (Exception ex) 
            {
                //handle exception here
            }
            return result.ToString();
        }