Using Win32 functions in Visual FoxPro Image Gallery
Code examples:
How to change display settings: screen resolution, screen refresh rate
Adding and deleting Scheduled Tasks using NetScheduleJob API functions
Capturing keyboard activity of another application with the Raw Input API (VFP9)
Custom GDI+ class
Converting Unicode data from the Clipboard to a character string using a given code page
Custom FTP Class for Visual FoxPro application
Custom HttpRequest class (WinINet)
Splash Screen for the VFP application
Displaying bitmap using the AlphaBlend function
Establishing connection using the SQLDriverConnect
Displaying animated images on FoxPro form with BitBlt and StretchBlt functions
How to put a vertical text scrolling on the form (a movie cast)
How to make a VFP form fading out when released (GDI+ version)
How to make a VFP form fading out when released (GDI version)
Using FlashWindowEx to flash the taskbar button of the VFP application
How to create non-blocking Winsock server
Using WM_COPYDATA for interprocess communication (VFP9)
Winsock: sending email messages (SMTP, port 25)
Creating a mailslot
Detecting changes in connections to removable drives (VFP9)
Sending a standard message with one or more attached files using default email client
Enumerating raw input devices attached to the system (keyboard, mouse, human interface device)
GDI+: copying to the Clipboard (a) image of active FoxPro window/form, (b) image file
Peer-to-peer LAN messenger built with Mailslot API functions
Capturing keyboard activity of another application with the Raw Input API (VFP9)

User rating: 0/10 (0 votes)
Rate this code sample:
  • ~
More code examples    Listed functions    Add comment     W32 Constants      Translate this page Printer friendly version of this code sample
Versions:
click to open
Before you begin:
In this code sample, VFP form registers for receiving the raw input from each and any keyboard type device connected to the computer. That includes keyboards, numeric keypads, keyboard wedge scanners and so on.

The testing is simple. Any text typed in another Windows application (like text editor, spreadsheet, browser) will be duplicated in an EditBox on the VFP form.

Note that this code sample requires VFP9 version of the BINDEVENT() function. The one that can handle Windows messages.

See also:
  • LanguageBar ActiveX control
  • Enumerating raw input devices attached to the system
  • Switching between keyboard layouts
  • Disabling mouse and keyboard input for the main VFP window
  • How to disable the Windows Clipboard
  •  
    using System;
    using System.Windows.Forms;
    using RawInputHook.DeviceManager;
     
    namespace RawInputHook.WinForm
    {
        public partial class RawInputMonitorForm : Form
        {
            public RawInputMonitorForm()
            {
                InitializeComponent();
     
                RawInputDeviceManager mgr = new RawInputDeviceManager();
                mgr.RawInputEvent += new RawInputEventHandler(OnRawInputEvent);
     
                mgr.AddKeyboardDevice(this.Handle);
                mgr.RegisterDevices();
     
                Application.AddMessageFilter(mgr);
            }
     
            void OnRawInputEvent(object sender, RawInputEventArgs e)
            {
                if (e.asciiCode != 0)
                {
                    switch (e.asciiCode)
                    {
                        case 13:
                            textBox1.Text += "\r\n";
                            break;
                        default:
                            textBox1.Text += (char)e.asciiCode;
                            break;
                    }
                }
            }
     
        }
    }
     
    // ======================================
     
    using System;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
     
    namespace RawInputHook.DeviceManager
    {
         public delegate void RawInputEventHandler(
            object sender, RawInputEventArgs e);
     
        public class RawInputDeviceManager : IMessageFilter
        {
            const int WM_INPUT = 0x00ff;
            public event RawInputEventHandler RawInputEvent;
            List < RAWINPUTDEVICE > devices = new List < RAWINPUTDEVICE > ();
     
            public void AddKeyboardDevice(IntPtr windowHandle)
            {
                AddDevice(1, 6, 0x100, windowHandle);
            }
     
            void AddDevice(ushort usagePage, ushort usage,
                Int32 flags, IntPtr windowHandle)
            {
                devices.Add(new RAWINPUTDEVICE(usagePage, usage,
                    flags, windowHandle));
            }
     
            public bool RegisterDevices()
            {
                if (devices.Count == 0) return false;
     
                RAWINPUTDEVICE[] d = devices.ToArray();
                bool result = RegisterRawInputDevices(d, devices.Count,
                    Marshal.SizeOf(typeof(RAWINPUTDEVICE)));
     
                return result;
            }
     
            void ProcessRawInput(IntPtr hRawInput)
            {
                RAWINPUT pData = new RAWINPUT();
                int pcbSize = Marshal.SizeOf(typeof(RAWINPUT));
     
                int result = GetRawInputData(hRawInput,
                    RawInputCommand.Input, out pData,
                    ref pcbSize, Marshal.SizeOf(typeof(RAWINPUTHEADER)));
     
                if (result != -1)
                {
                    if (pData.Header.Type == RawInputType.Keyboard)
                    {
                        if ((pData.Keyboard.Flags == 0) || 
                            (pData.Keyboard.Flags == 2))
                        {
                            int asciiCode = VKeyToChar(
                                pData.Keyboard.VirtualKey,
                                pData.Keyboard.MakeCode);
     
                            RawInputEvent(this, 
                                new RawInputEventArgs(pData, asciiCode));
                        }
                    }
                }
            }
     
            int VKeyToChar(int virtKey, int scanCode)
            {
                int asciiCode = 0;
                byte[] kbdState = new byte[256];
                GetKeyboardState(kbdState);
                ToAscii(virtKey, scanCode, kbdState, ref asciiCode, 0);
                return asciiCode;
            }
     
            #region IMessageFilter Members
     
            public bool PreFilterMessage(ref Message m)
            {
                if (m.Msg == WM_INPUT)
                {
                    if (m.WParam != (IntPtr)0) //the app is on background
                    {
                        if (RawInputEvent != null) //event implemented
                        {
                            ProcessRawInput(m.LParam);
                            return true; //stop the message
                        }
                    }
                }
                return false; //allow the message to continue
            }
     
            #endregion
     
            [DllImport("user32.dll")]
            static extern bool RegisterRawInputDevices(
                [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] 
                RAWINPUTDEVICE[] pRawInputDevices,
                int uiNumDevices, int cbSize);
     
            [DllImport("user32.dll")]
            static extern int GetRawInputData(IntPtr hRawInput,
                RawInputCommand uiCommand, out RAWINPUT pData,
                ref int pcbSize, int cbSizeHeader);
     
            [DllImport("user32.dll")]
            static extern int GetKeyboardState(byte[] lpKeyState);
     
            [DllImport("user32.dll")]
            static extern int MapVirtualKey(int uCode, int uMapType);
     
            [DllImport("user32.dll")]
            static extern int ToAscii(int uVirtKey, int uScanCode,
                byte[] lpKeyState, ref int lpChar, int uFlags);
        }
     
        public class RawInputEventArgs : EventArgs
        {
            public RAWINPUT rawInput;
            public int asciiCode = 0;
            public RawInputEventArgs(RAWINPUT rawInput, int asciiCode)
            {
                this.rawInput = rawInput;
                this.asciiCode = asciiCode;
            }
        }
     
        [StructLayout(LayoutKind.Sequential)]
        struct RAWINPUTDEVICE
        {
            public ushort UsagePage;
            public ushort Usage;
            public Int32 Flags;
            public IntPtr WindowHandle;
            public RAWINPUTDEVICE(ushort usagePage, ushort usage,
                Int32 flags, IntPtr windowHandle)
            {
                UsagePage = usagePage;
                Usage = usage;
                Flags = flags;
                WindowHandle = windowHandle;
            }
        }
     
        [StructLayout(LayoutKind.Explicit)]
        public struct RAWINPUT
        {
            [FieldOffset(0)]
            public RAWINPUTHEADER Header;
            [FieldOffset(16)]
            public RAWKEYBOARD Keyboard;
            //mouse and HID parts omitted
        }
     
        [StructLayout(LayoutKind.Sequential)]
        public struct RAWINPUTHEADER
        {
            public RawInputType Type;
            public int Size;
            public IntPtr Device;
            public IntPtr wParam;
        }
     
        [StructLayout(LayoutKind.Sequential)]
        public struct RAWKEYBOARD
        {
            public ushort MakeCode;
            public ushort Flags;
            public ushort Reserved;
            public ushort VirtualKey;
            public int Message;
            public int ExtraInformation;
        }
     
        public enum RawInputType
        {
            Mouse = 0,
            Keyboard = 1,
            HID = 2
        }
     
        enum RawInputCommand
        {
            Input = 0x10000003,
            Header = 0x10000005
        }
    }
     

    User rating: 0/10 (0 votes)
    Rate this code sample:
    • ~
    6703 bytes  
    Created: 2011-01-06 12:31:59  
    Modified: 2011-02-22 03:05:19  
    Visits in 7 days: 314  
    Listed functions:
    CallWindowProc
    GetKeyboardState
    GetLastError
    GetRawInputData
    GetWindowLong
    MapVirtualKey
    RegisterRawInputDevices
    ToAscii
    Printer friendly API declarations
    My comment:
    By default, no application receives raw input. For doing that, an application must register a device type it wants to get data from. When registered, an application receives the raw input through the WM_INPUT messages.

    User input comes not just from keyboard and mouse, but also from a joystick, a touch screen, a microphone, and other devices collectively known as Human Interface Devices (HIDs).

    Global keyboard and mouse hooks can produce similar results.

    In case of multiple input devices of same type, the Raw Input API has means to separate the input (i.g. keystrokes, mouse events) by source.

    * * *
    Curiously: initially I chose registering keystrokes on KeyUps. And switched to KeyDowns after finding that fast typed keystrokes sometimes get released not in the sequence of pressing.
    Word Index links for this example:
    Translate this page:
      Spanish    Portuguese    German    French    Italian  
    FreeTranslation.com offers instant, free translations of text or web pages.
    User Contributed Notes:
    There are no notes on this subject.


    Copyright © 2001-2013 News2News, Inc. Before reproducing or distributing any data from this site please ask for an approval from its owner. Unless otherwise specified, this page is for your personal and non-commercial use. The information on this page is presented AS IS, meaning that you may use it at your own risk. Microsoft Visual FoxPro and Windows are trade marks of Microsoft Corp. All other trademarks are the property of their respective owners. 

    Privacy policy
    Credits: PHP (4.4.9), an HTML-embedded scripting language, MySQL (5.1.55-log), the Open Source standard SQL database, AceHTML Freeware Version 4, freeware HTML Editor of choice.   Hosted by Korax Online Inc.
    Last Topics Visited (54.224.75.101)
    4 sec.Function: 'CeFindFirstDatabaseEx'
    3.11 hrs.Example: 'Drawing cursors for the classes defined by the system (preregistered): BUTTON, EDIT, LISTBOX etc.'
     Function: 'SCardEstablishContext'
    5.88 hrs.Function: 'GetEnvironmentVariable'
    Function group: 'Process and Thread'
     Function: 'FindFirstPrinterChangeNotification'
    10.37 hrs.Example: 'How to play AVI file on the _screen'
    Language: 'Visual FoxPro'
     Function: 'FindFirstFile'
    Google
    Advertise here!