Beispiel #1
0
        private bool ProcessMouseInput(InputData rawBuffer)
        {
            ushort usFlags       = rawBuffer.data.mouse.usFlags;
            ushort usButtonFlags = rawBuffer.data.mouse.usButtonFlags;
            short  sButtonData   = rawBuffer.data.mouse.usButtonData;
            int    lLastX        = rawBuffer.data.mouse.lLastX;
            int    lLastY        = rawBuffer.data.mouse.lLastY;

            RawMouseDevice device;

            lock (_lock)
            {
                if (!_mouseList.TryGetValue(rawBuffer.header.hDevice, out device))
                {
                    Debug.WriteLine("Handle: {0} was not in the device list.", rawBuffer.header.hDevice);
                    return(false);
                }
            }

            EventHandler <RawInputMouseEventArgs> mouseClicked = MouseClickedDelegate;

            if (mouseClicked != null)
            {
                var rawInputEventArgs = new RawInputMouseEventArgs(device, usFlags, usButtonFlags, sButtonData, lLastX, lLastY);
                mouseClicked(this, rawInputEventArgs);
                if (rawInputEventArgs.Handled)
                {
                    MSG msg;
                    Win32Methods.PeekMessage(out msg, IntPtr.Zero, Win32Consts.WM_MOUSEFIRST, Win32Consts.WM_MOUSELAST, Win32Consts.PM_REMOVE);
                }
                return(rawInputEventArgs.Handled);
            }
            return(false);
        }
Beispiel #2
0
        private bool ProcessRawInput(IntPtr hdevice)
        {
            if (_keyboardList.Count == 0 && _mouseList.Count == 0 && _hidList.Count == 0)
            {
                Debug.WriteLine("KeyboardCount: {0}, MouseCount: {1}, HidCount: {2}", _keyboardList.Count, _mouseList.Count, _hidList.Count);
                return(false);
            }
            int size = 0;

            Win32Methods.GetRawInputData(hdevice, DataCommand.RID_INPUT, IntPtr.Zero, ref size, Marshal.SizeOf(typeof(RawInputHeader)));
            InputData rawBuffer;

            if (Win32Methods.GetRawInputData(hdevice, DataCommand.RID_INPUT, out rawBuffer, ref size, Marshal.SizeOf(typeof(RawInputHeader))) != size)
            {
                Debug.WriteLine("Error getting the rawinput buffer");
                return(false);
            }

            switch ((RawDeviceType)rawBuffer.header.dwType)
            {
            case RawDeviceType.Mouse:
                return(ProcessMouseInput(rawBuffer));

            case RawDeviceType.Hid:
                return(ProcessHidInput(rawBuffer));

            case RawDeviceType.Keyboard:
                return(ProcessKeyboardInput(rawBuffer));
            }
            return(false);
        }
Beispiel #3
0
 protected RawInput(IntPtr handle, RawInputCaptureMode captureMode)
 {
     RawInputDevice[] array =
     {
         new RawInputDevice
         {
             UsagePage = HidUsagePage.GENERIC,
             Usage     = HidUsage.Keyboard,
             Flags     = (captureMode == RawInputCaptureMode.Foreground ? RawInputDeviceFlags.NONE : RawInputDeviceFlags.INPUTSINK) | RawInputDeviceFlags.DEVNOTIFY,
             Target    = IntPtr.Zero
         },
         new RawInputDevice
         {
             UsagePage = HidUsagePage.GENERIC,
             Usage     = HidUsage.Mouse,
             Flags     = (captureMode == RawInputCaptureMode.Foreground ? RawInputDeviceFlags.NONE : RawInputDeviceFlags.INPUTSINK) | RawInputDeviceFlags.DEVNOTIFY,
             Target    = IntPtr.Zero
         },
         new RawInputDevice
         {
             UsagePage = HidUsagePage.GENERIC,
             Usage     = HidUsage.Gamepad,
             Flags     = (captureMode == RawInputCaptureMode.Foreground ? RawInputDeviceFlags.NONE : RawInputDeviceFlags.INPUTSINK) | RawInputDeviceFlags.DEVNOTIFY,
             Target    = IntPtr.Zero
         }
     };
     if (!Win32Methods.RegisterRawInputDevices(array, (uint)array.Length, (uint)Marshal.SizeOf(array[0])))
     {
         throw new ApplicationException("Failed to register raw input device(s).", new Win32Exception());
     }
     EnumerateDevices();
     _devNotifyHandle = RegisterForDeviceNotifications(handle);
 }
Beispiel #4
0
 public void EnumerateHid()
 {
     lock (_lock)
     {
         _hidList.Clear();
         uint devices = 0u;
         int  size    = Marshal.SizeOf(typeof(RawInputDeviceList));
         if (Win32Methods.GetRawInputDeviceList(IntPtr.Zero, ref devices, (uint)size) != 0u)
         {
             throw new Win32Exception(Marshal.GetLastWin32Error());
         }
         IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(size * devices));
         try
         {
             Win32Methods.GetRawInputDeviceList(pRawInputDeviceList, ref devices, (uint)size);
             int index = 0;
             while (index < devices)
             {
                 RawHidDevice device = GetHid(pRawInputDeviceList, size, index);
                 if (device != null && !_hidList.ContainsKey(device.Handle))
                 {
                     Debug.WriteLine("Added Hid; Handle: {0}, Name: {1}, Type: {2}, Description: {3}", (uint)device.Handle, device.Name, device.Type, device.Description);
                     _hidList.Add(device.Handle, device);
                 }
                 index++;
             }
         }
         finally
         {
             Marshal.FreeHGlobal(pRawInputDeviceList);
         }
         NumberOfHid = _hidList.Count;
     }
 }
        InterceptKeys()
        {
            keyStream = Observable.Create <InterceptKeyEventArgs>(observer =>
            {
                Debug.Write("Subscribed to keys");
                IntPtr hookId = IntPtr.Zero;
                // Need to hold onto this callback, otherwise it will get GC'd as it is an unmanged callback
                callback = (nCode, wParam, lParam) =>
                {
                    if (nCode >= 0)
                    {
                        var eventArgs = CreateEventArgs(wParam, lParam);
                        observer.OnNext(eventArgs);
                        if (eventArgs.Handled)
                        {
                            return((IntPtr)1);
                        }
                    }

                    // ReSharper disable once AccessToModifiedClosure
                    return(Win32Methods.CallNextHookEx(hookId, nCode, wParam, lParam));
                };
                hookId = SetHook(callback);
                return(Disposable.Create(() =>
                {
                    Debug.Write("Unsubscribed from keys");
                    Win32Methods.UnhookWindowsHookEx(hookId);
                    callback = null;
                }));
            })
                        .Publish().RefCount();
        }
        public static IDictionary<IntPtr, RawKeyboardDevice> GetDevices()
        {
            var deviceList = new Dictionary<IntPtr, RawKeyboardDevice>();

            var rawKeyboardDevice = new RawKeyboardDevice("Global Keyboard", RawDeviceType.Keyboard, IntPtr.Zero,
                "Fake Keyboard. Some keys (ZOOM, MUTE, VOLUMEUP, VOLUMEDOWN) are sent to rawinput with a handle of zero.");
            deviceList.Add(rawKeyboardDevice.Handle, rawKeyboardDevice);
            uint devices = 0u;
            int size = Marshal.SizeOf(typeof(RawInputDeviceList));
            if (Win32Methods.GetRawInputDeviceList(IntPtr.Zero, ref devices, (uint)size) != 0u)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(size * devices));
            try
            {
                Win32Methods.GetRawInputDeviceList(pRawInputDeviceList, ref devices, (uint)size);
                int index = 0;
                while (index < devices)
                {
                    RawKeyboardDevice device = GetDevice(pRawInputDeviceList, size, index);
                    if (device != null && !deviceList.ContainsKey(device.Handle))
                    {
                        deviceList.Add(device.Handle, device);
                    }
                    index++;
                }
            }
            finally
            {
                Marshal.FreeHGlobal(pRawInputDeviceList);
            }

            return deviceList;
        }
 private static RawKeyboardDevice GetDevice(IntPtr pRawInputDeviceList, int dwSize, int index)
 {
     uint size = 0u;
     // On Window 8 64bit when compiling against .Net > 3.5 using .ToInt32 you will generate an arithmetic overflow. Leave as it is for 32bit/64bit applications
     var rawInputDeviceList = (RawInputDeviceList)Marshal.PtrToStructure(new IntPtr(pRawInputDeviceList.ToInt64() + dwSize * index), typeof(RawInputDeviceList));
     Win32Methods.GetRawInputDeviceInfo(rawInputDeviceList.hDevice, RawInputDeviceInfo.RIDI_DEVICENAME, IntPtr.Zero, ref size);
     if (size <= 0u)
     {
         return null;
     }
     IntPtr intPtr = Marshal.AllocHGlobal((int)size);
     try
     {
         Win32Methods.GetRawInputDeviceInfo(rawInputDeviceList.hDevice, RawInputDeviceInfo.RIDI_DEVICENAME, intPtr, ref size);
         string device = Marshal.PtrToStringAnsi(intPtr);
         if (rawInputDeviceList.dwType == DeviceType.RimTypekeyboard ||
             rawInputDeviceList.dwType == DeviceType.RimTypeHid)
         {
             string deviceDescription = Win32Methods.GetDeviceDescription(device);
             return new RawKeyboardDevice(Marshal.PtrToStringAnsi(intPtr),
                 (RawDeviceType)rawInputDeviceList.dwType, rawInputDeviceList.hDevice, deviceDescription);
         }
     }
     finally
     {
         if (intPtr != IntPtr.Zero)
         {
             Marshal.FreeHGlobal(intPtr);
         }
     }
     return null;
 }
Beispiel #8
0
 public void EnumerateKeyboards()
 {
     lock (_lock)
     {
         _keyboardList.Clear();
         var rawKeyboardDevice = new RawKeyboardDevice("Global Keyboard", RawDeviceType.Keyboard, IntPtr.Zero, "Fake Keyboard. Some keys (ZOOM, MUTE, VOLUMEUP, VOLUMEDOWN) are sent to rawinput with a handle of zero.");
         _keyboardList.Add(rawKeyboardDevice.Handle, rawKeyboardDevice);
         uint devices = 0u;
         int  size    = Marshal.SizeOf(typeof(RawInputDeviceList));
         if (Win32Methods.GetRawInputDeviceList(IntPtr.Zero, ref devices, (uint)size) != 0u)
         {
             throw new Win32Exception(Marshal.GetLastWin32Error());
         }
         IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(size * devices));
         try
         {
             Win32Methods.GetRawInputDeviceList(pRawInputDeviceList, ref devices, (uint)size);
             int index = 0;
             while (index < devices)
             {
                 RawKeyboardDevice device = GetKeyboard(pRawInputDeviceList, size, index);
                 if (device != null && !_keyboardList.ContainsKey(device.Handle))
                 {
                     _keyboardList.Add(device.Handle, device);
                 }
                 index++;
             }
         }
         finally
         {
             Marshal.FreeHGlobal(pRawInputDeviceList);
         }
         NumberOfKeyboards = _keyboardList.Count;
     }
 }
Beispiel #9
0
 public void EnumerateMice()
 {
     lock (_lock)
     {
         _mouseList.Clear();
         uint devices = 0u;
         int  size    = Marshal.SizeOf(typeof(RawInputDeviceList));
         if (Win32Methods.GetRawInputDeviceList(IntPtr.Zero, ref devices, (uint)size) != 0u)
         {
             throw new Win32Exception(Marshal.GetLastWin32Error());
         }
         IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(size * devices));
         try
         {
             Win32Methods.GetRawInputDeviceList(pRawInputDeviceList, ref devices, (uint)size);
             int index = 0;
             while (index < devices)
             {
                 RawMouseDevice device = GetMouse(pRawInputDeviceList, size, index);
                 if (device != null && !_mouseList.ContainsKey(device.Handle))
                 {
                     _mouseList.Add(device.Handle, device);
                 }
                 index++;
             }
         }
         finally
         {
             Marshal.FreeHGlobal(pRawInputDeviceList);
         }
         NumberOfMice = _mouseList.Count;
     }
 }
Beispiel #10
0
 public void Activate(IntPtr hWndParent, RECT[] pRect, int bModal)
 {
     if (pane != null)
     {
         Win32Methods.SetParent(pane.Handle, hWndParent);
     }
 }
Beispiel #11
0
        private static IntPtr RegisterForDeviceNotifications(IntPtr parent)
        {
            IntPtr notifyHandle = IntPtr.Zero;
            BroadcastDeviceInterface broadcastDeviceInterface = default(BroadcastDeviceInterface);

            broadcastDeviceInterface.dbcc_size           = Marshal.SizeOf(broadcastDeviceInterface);
            broadcastDeviceInterface.BroadcastDeviceType = BroadcastDeviceType.DBT_DEVTYP_DEVICEINTERFACE;
            broadcastDeviceInterface.dbcc_classguid      = DeviceInterfaceHid;
            IntPtr interfacePtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(BroadcastDeviceInterface)));

            try
            {
                Marshal.StructureToPtr(broadcastDeviceInterface, interfacePtr, false);
                notifyHandle = Win32Methods.RegisterDeviceNotification(parent, interfacePtr,
                                                                       DeviceNotification.DEVICE_NOTIFY_WINDOW_HANDLE);
            }
            catch (Exception ex)
            {
                Debug.Print("Registration for device notifications Failed. Error: {0}", Marshal.GetLastWin32Error());
                Debug.Print(ex.StackTrace);
            }
            finally
            {
                Marshal.FreeHGlobal(interfacePtr);
            }

            if (notifyHandle == IntPtr.Zero)
            {
                Debug.Print("Registration for device notifications Failed. Error: {0}", Marshal.GetLastWin32Error());
            }
            return(notifyHandle);
        }
Beispiel #12
0
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            var hwnd = new WindowInteropHelper(this).Handle;

            Win32Methods.SetWindowExTransparent(hwnd);

            var timer = new Timer(100);

            timer.Elapsed +=
                (s, x) =>
            {
                SetWindowPos(hwnd,
                             HWND.TOPMOST,
                             0, 0, 0, 0,
                             (uint)(SWP.NOMOVE | SWP.NOSIZE | SWP.SHOWWINDOW));
            };

            timer.Start();

            var vm = ((KeyShowViewModel)DataContext);

            Left = vm.Settings.Left;
            vm.Settings.LeftChanged += SettingsLeftChanged;
            WindowState              = WindowState.Maximized;
        }
Beispiel #13
0
 public int CreatePaneWindow(IntPtr hwndParent, int x, int y, int cx, int cy, out IntPtr hwnd)
 {
     Win32Methods.SetParent(Handle, hwndParent);
     hwnd = Handle;
     Size = new Size(cx - x, cy - y);
     return(VSConstants.S_OK);
 }
Beispiel #14
0
        public Task ActivateAsync(IntPtr hWndParent, Rectangle rect, bool modal)
        {
            CreateControl();
            Win32Methods.SetParent(Handle, hWndParent);

            return(TplExtensions.CompletedTask);
        }
Beispiel #15
0
        private bool ProcessRawInput(IntPtr hdevice)
        {
            if (_deviceList.Count == 0)
            {
                return(false);
            }
            var size = 0;

            Win32Methods.GetRawInputData(hdevice, DataCommand.RID_INPUT, IntPtr.Zero, ref size,
                                         Marshal.SizeOf(typeof(RawInputHeader)));
            InputData rawBuffer;

            if (
                Win32Methods.GetRawInputData(hdevice, DataCommand.RID_INPUT, out rawBuffer, ref size,
                                             Marshal.SizeOf(typeof(RawInputHeader))) != size)
            {
                Debug.WriteLine("Error getting the rawinput buffer");
                return(false);
            }
            int vKey     = rawBuffer.data.keyboard.VKey;
            int makecode = rawBuffer.data.keyboard.Makecode;
            int flags    = rawBuffer.data.keyboard.Flags;

            if (vKey == Win32Consts.KEYBOARD_OVERRUN_MAKE_CODE)
            {
                return(false);
            }

            RawKeyboardDevice device;

            lock (_lock)
            {
                if (!_deviceList.TryGetValue(rawBuffer.header.hDevice, out device))
                {
                    Debug.WriteLine("Handle: {0} was not in the device list.", rawBuffer.header.hDevice);
                    return(false);
                }
            }

            var isE0BitSet    = (flags & Win32Consts.RI_KEY_E0) != 0;
            var isBreakBitSet = (flags & Win32Consts.RI_KEY_BREAK) != 0;

            var message    = rawBuffer.data.keyboard.Message;
            var key        = KeyInterop.KeyFromVirtualKey(AdjustVirtualKey(rawBuffer, vKey, isE0BitSet, makecode));
            var keyPressed = KeyPressed;

            if (keyPressed != null)
            {
                var rawInputEventArgs = new RawInputEventArgs(device, isBreakBitSet ? KeyPressState.Up : KeyPressState.Down,
                                                              message, key, vKey);
                keyPressed(this, rawInputEventArgs);
                if (rawInputEventArgs.Handled)
                {
                    MSG msg;
                    Win32Methods.PeekMessage(out msg, IntPtr.Zero, Win32Consts.WM_KEYDOWN, Win32Consts.WM_KEYUP, Win32Consts.PM_REMOVE);
                }
                return(rawInputEventArgs.Handled);
            }
            return(false);
        }
Beispiel #16
0
        public MpqArchive(MemoryMappedFile file, FileAccess accessType)
        {
            _accessType = accessType;
            string fileName = Win32Methods.GetFileNameOfMemoryMappedFile(file);

            if (fileName == null)
            {
                throw new ArgumentException("Could not retrieve the name of the file to initialize.");
            }

            SFileOpenArchiveFlags flags = SFileOpenArchiveFlags.TypeIsMemoryMapped;

            if (accessType == FileAccess.Read)
            {
                flags |= SFileOpenArchiveFlags.AccessReadOnly;
            }
            else
            {
                flags |= SFileOpenArchiveFlags.AccessReadWriteShare;
            }

            // constant 2 = SFILE_OPEN_HARD_DISK_FILE
            if (!NativeMethods.SFileOpenArchive(fileName, 2, flags, out _handle))
            {
                throw new Win32Exception(); // Implicitly calls GetLastError
            }
        }
 public void Dispose()
 {
     GC.SuppressFinalize(this);
     if (_devNotifyHandle != IntPtr.Zero)
     {
         Win32Methods.UnregisterDeviceNotification(_devNotifyHandle);
         _devNotifyHandle = IntPtr.Zero;
     }
 }
Beispiel #18
0
        private void GameWindow_Idle(object sender, EventArgs e)
        {
            Win32Message msg;

            while (!Win32Methods.PeekMessage(out msg, IntPtr.Zero, 0, 0, 0))
            {
                Idle();
            }
        }
Beispiel #19
0
 static IntPtr SetHook(Win32Methods.LowLevelKeyboardProc proc)
 {
     //TODO: This requires FullTrust to use the Process class - is there any options for doing this in MediumTrust?
     //
     using (Process curProcess = Process.GetCurrentProcess())
     using (ProcessModule curModule = curProcess.MainModule)
     {
         return Win32Methods.SetWindowsHookEx(Win32Methods.WH_KEYBOARD_LL, proc, Win32Methods.GetModuleHandle(curModule.ModuleName), 0);
     }
 }
Beispiel #20
0
        public Task <int> TranslateAcceleratorAsync(MSG msg)
        {
            if ((msg.message < WM.WM_KEYFIRST || msg.message > WM.WM_KEYLAST) &&
                (msg.message < WM.WM_MOUSEFIRST || msg.message > WM.WM_MOUSELAST))
            {
                return(Task.FromResult(VSConstants.S_FALSE));
            }

            return(Task.FromResult(Win32Methods.IsDialogMessageA(Handle, ref msg).ToVSConstant()));
        }
Beispiel #21
0
 static IntPtr SetHook(Win32Methods.LowLevelKeyboardProc proc)
 {
     //TODO: This requires FullTrust to use the Process class - is there any options for doing this in MediumTrust?
     //
     using (Process curProcess = Process.GetCurrentProcess())
         using (ProcessModule curModule = curProcess.MainModule)
         {
             return(Win32Methods.SetWindowsHookEx(Win32Methods.WH_KEYBOARD_LL, proc, Win32Methods.GetModuleHandle(curModule.ModuleName), 0));
         }
 }
        public int CreatePaneWindow(IntPtr hwndParent, int x, int y, int cx, int cy, out IntPtr hwnd)
        {
            Win32Methods.SetParent(Handle, hwndParent);
            hwnd = Handle;
            Size = new System.Drawing.Size(cx - x, cy - y);

            // Note, logical views map to the tab control panes.

            return(VSConstants.S_OK);
        }
Beispiel #23
0
 ///--------------------------------------------------------------------------------------------
 /// <summary>
 /// IPropertyPage
 /// This is called before our form is shown but after SetObjects is called.
 /// This is the place from which the form can populate itself using the information available
 /// in CPS.
 /// </summary>
 ///--------------------------------------------------------------------------------------------
 public void Activate(IntPtr hWndParent, RECT[] pRect, int bModal)
 {
     AdviseDebugger();
     SuspendLayout();
     // Initialization can cause some events to be fired when we change some values
     // so we use this flag (_ignoreEvents) to notify IsDirty to ignore
     // any changes that happen during initialization
     Win32Methods.SetParent(Handle, hWndParent);
     ResumeLayout();
 }
Beispiel #24
0
 static IntPtr SetHook(Win32Methods.LowLevelKeyboardProc proc)
 {
     // NOTE: This requires FullTrust to use the Process class.
     //       There don't seem to be alternatives to achieving this in
     //       MediumTrust environment which is fine because that's a
     //       concept that has long been obsoleted. But just a warning
     //       if you ever try and run Carnac in that sort of way.
     using (Process curProcess = Process.GetCurrentProcess())
         using (ProcessModule curModule = curProcess.MainModule)
         {
             return(Win32Methods.SetWindowsHookEx(Win32Methods.WH_KEYBOARD_LL, proc, Win32Methods.GetModuleHandle(curModule.ModuleName), 0));
         }
 }
Beispiel #25
0
        public static ChangeJournal Open(DriveInfo driveInfo)
        {
            if (driveInfo == null)
            {
                throw new ArgumentNullException(nameof(driveInfo));
            }

            var volume = VolumeHelper.GetValidVolumePath(driveInfo);
            var handle = Win32Methods.CreateFile(volume, FileAccess.Read, FileShare.Read | FileShare.Write, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);

            if (handle.IsInvalid)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            return(new ChangeJournal(handle));
        }
Beispiel #26
0
        /// <summary>
        /// Creates a window pane
        /// </summary>
        /// <returns>Return code</returns>
        int IVsWindowPane.CreatePaneWindow(System.IntPtr hwndParent, int x, int y, int cx, int cy, out System.IntPtr hwnd)
        {
            Win32Methods.SetParent(Handle, hwndParent);
            hwnd = Handle;

            Debug.Assert(TrackSelection != null, "Unable to register in property window!");
            if (TrackSelection != null)
            {
                TrackSelection.OnSelectChange(SelectionContainer);
            }

            Size = new System.Drawing.Size(cx - x, cy - y);

            // Loading configuration settings
            LoadSettings();

            return(VSConstants.S_OK);
        }
Beispiel #27
0
        public NtStatus SetFileTime(string fileName, DateTime?creationTime, DateTime?lastAccessTime, DateTime?lastWriteTime, IDokanFileInfo info)
        {
            try
            {
                if (info.Context is FileStream stream)
                {
                    var ct  = creationTime?.ToFileTime() ?? 0;
                    var lat = lastAccessTime?.ToFileTime() ?? 0;
                    var lwt = lastWriteTime?.ToFileTime() ?? 0;
                    if (Win32Methods.SetFileTime(stream.SafeFileHandle, ref ct, ref lat, ref lwt))
                    {
                        return(DokanResult.Success);
                    }
                    throw Marshal.GetExceptionForHR(Marshal.GetLastWin32Error());
                }

                var filePath = GetDiskPath(fileName);

                if (creationTime.HasValue)
                {
                    File.SetCreationTime(filePath, creationTime.Value);
                }

                if (lastAccessTime.HasValue)
                {
                    File.SetLastAccessTime(filePath, lastAccessTime.Value);
                }

                if (lastWriteTime.HasValue)
                {
                    File.SetLastWriteTime(filePath, lastWriteTime.Value);
                }

                return(DokanResult.Success);
            }
            catch (UnauthorizedAccessException)
            {
                return(DokanResult.AccessDenied);
            }
            catch (FileNotFoundException)
            {
                return(DokanResult.FileNotFound);
            }
        }
Beispiel #28
0
        public bool ProcessRawInput(IntPtr hdevice)
        {
            int size = 0;

            Win32Methods.GetRawInputData(hdevice, DataCommand.RID_INPUT, IntPtr.Zero, ref size, Marshal.SizeOf(typeof(RawInputHeader)));
            InputData rawBuffer;

            if (Win32Methods.GetRawInputData(hdevice, DataCommand.RID_INPUT, out rawBuffer, ref size, Marshal.SizeOf(typeof(RawInputHeader))) != size)
            {
                Debug.WriteLine("Error getting the rawinput buffer");
                return(false);
            }

            int vKey     = rawBuffer.data.keyboard.VKey;
            int makecode = rawBuffer.data.keyboard.Makecode;
            int flags    = rawBuffer.data.keyboard.Flags;

            if (vKey == Win32Consts.KEYBOARD_OVERRUN_MAKE_CODE)
            {
                return(false);
            }

            var  isE0BitSet    = ((flags & Win32Consts.RI_KEY_E0) != 0);
            bool isBreakBitSet = (flags & Win32Consts.RI_KEY_BREAK) != 0;

            uint message = rawBuffer.data.keyboard.Message;
            Key  key     = KeyInterop.KeyFromVirtualKey(AdjustVirtualKey(rawBuffer, vKey, isE0BitSet, makecode));
            EventHandler <RawKeyEventArgs> keyPressed = KeyPressed;

            if (keyPressed != null)
            {
                var rawInputEventArgs = new RawKeyEventArgs(rawBuffer.header.hDevice, isBreakBitSet ? KeyPressState.Up : KeyPressState.Down, message, key, vKey);
                keyPressed(this, rawInputEventArgs);
                if (rawInputEventArgs.Handled)
                {
                    //Remove the message
                    MSG msg;
                    Win32Methods.PeekMessage(out msg, IntPtr.Zero, Win32Consts.WM_KEYDOWN, Win32Consts.WM_KEYUP, Win32Consts.PM_REMOVE);
                }
                return(rawInputEventArgs.Handled);
            }
            return(false);
        }
 public RawKeyboard(IntPtr hwnd, bool captureOnlyInForeground)
 {
     RawInputDevice[] array =
     {
         new RawInputDevice
         {
             UsagePage = HidUsagePage.GENERIC,
             Usage     = HidUsage.Keyboard,
             Flags     = (captureOnlyInForeground ? RawInputDeviceFlags.NONE : RawInputDeviceFlags.INPUTSINK) | RawInputDeviceFlags.DEVNOTIFY,
             Target    = hwnd
         }
     };
     if (!Win32Methods.RegisterRawInputDevices(array, (uint)array.Length, (uint)Marshal.SizeOf(array[0])))
     {
         throw new ApplicationException("Failed to register raw input device(s).", new Win32Exception());
     }
     EnumerateDevices();
     _devNotifyHandle = RegisterForDeviceNotifications(hwnd);
 }
Beispiel #30
0
        public IDisposable Subscribe(IObserver <InterceptKeyEventArgs> observer)
        {
            Debug.WriteLine("Subscribed");
            IDisposable dispose = subject.Subscribe(observer);

            subscriberCount++;
            if (subscriberCount == 1)
            {
                hookId = SetHook(callback);
            }
            return(new DelegateDisposable(() =>
            {
                subscriberCount--;
                if (subscriberCount == 0)
                {
                    Win32Methods.UnhookWindowsHookEx(hookId);
                }
                dispose.Dispose();
            }));
        }
Beispiel #31
0
        IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0)
            {
                bool alt     = (Control.ModifierKeys & Keys.Alt) != 0;
                bool control = (Control.ModifierKeys & Keys.Control) != 0;
                bool shift   = (Control.ModifierKeys & Keys.Shift) != 0;
                bool keyDown = wParam == (IntPtr)Win32Methods.WM_KEYDOWN;
                bool keyUp   = wParam == (IntPtr)Win32Methods.WM_KEYUP;
                int  vkCode  = Marshal.ReadInt32(lParam);
                var  key     = (Keys)vkCode;
                //http://msdn.microsoft.com/en-us/library/windows/desktop/ms646286(v=vs.85).aspx
                if (key != Keys.RMenu && key != Keys.LMenu && wParam == (IntPtr)Win32Methods.WM_SYSKEYDOWN)
                {
                    alt     = true;
                    keyDown = true;
                }
                if (key != Keys.RMenu && key != Keys.LMenu && wParam == (IntPtr)Win32Methods.WM_SYSKEYUP)
                {
                    alt   = true;
                    keyUp = true;
                }

                var interceptKeyEventArgs = new InterceptKeyEventArgs(
                    key,
                    keyDown ?
                    KeyDirection.Down: keyUp
                    ? KeyDirection.Up: KeyDirection.Unknown,
                    alt, control, shift);

                subject.OnNext(interceptKeyEventArgs);
                Debug.Write(key);
                if (interceptKeyEventArgs.Handled)
                {
                    Debug.WriteLine(" handled");
                    return((IntPtr)1); //handled
                }
            }

            return(Win32Methods.CallNextHookEx(hookId, nCode, wParam, lParam));
        }