├── Autofarmer
├── MouseKeyHook
│ ├── HotKeys
│ │ ├── HotKeySetsListener.cs
│ │ ├── HotKeyArgs.cs
│ │ ├── HotKeySetCollection.cs
│ │ ├── ReadMe.txt
│ │ └── HotKeySet.cs
│ ├── Implementation
│ │ ├── Callback.cs
│ │ ├── Subscribe.cs
│ │ ├── AppEventFacade.cs
│ │ ├── GlobalEventFacade.cs
│ │ ├── AppMouseListener.cs
│ │ ├── BaseListener.cs
│ │ ├── ButtonSet.cs
│ │ ├── KeysExtensions.cs
│ │ ├── AppKeyListener.cs
│ │ ├── GlobalKeyListener.cs
│ │ ├── KeyListener.cs
│ │ ├── Chord.cs
│ │ ├── GlobalMouseListener.cs
│ │ ├── KeyboardState.cs
│ │ ├── EventFacade.cs
│ │ └── MouseListener.cs
│ ├── IKeyboardMouseEvents.cs
│ ├── WinApi
│ │ ├── CallbackData.cs
│ │ ├── HookResult.cs
│ │ ├── HookProcedureHandle.cs
│ │ ├── MouseNativeMethods.cs
│ │ ├── HookIds.cs
│ │ ├── KeyboardHookStruct.cs
│ │ ├── Point.cs
│ │ ├── ThreadNativeMethods.cs
│ │ ├── MouseStruct.cs
│ │ ├── HookProcedure.cs
│ │ ├── HotkeysNativeMethods.cs
│ │ ├── AppMouseStruct.cs
│ │ ├── HookHelper.cs
│ │ ├── HookNativeMethods.cs
│ │ └── Messages.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ ├── Hook.cs
│ ├── MouseKeyHook.nuspec
│ ├── Sequence.cs
│ ├── IKeyboardEvents.cs
│ ├── SequenceBase.cs
│ ├── IMouseEvents.cs
│ ├── KeyPressEventArgsExt.cs
│ ├── KeyCombinationExtensions.cs
│ ├── Combination.cs
│ ├── KeyEventArgsExt.cs
│ └── MouseEventExtArgs.cs
├── App.config
├── Properties
│ ├── Settings.settings
│ ├── Settings.Designer.cs
│ ├── AssemblyInfo.cs
│ ├── Resources.Designer.cs
│ └── Resources.resx
├── Program.cs
├── Autofarm.Multibox.cs
├── GlobalMouseHook.cs
├── MouseHook.cs
├── Autofarm.resx
├── Autofarmer.csproj
└── globalKeyboardHook.cs
├── LICENSE
├── Autofarmer.sln
├── README.md
├── MouseHook.cs
├── .gitignore
└── KeyboardHook.cs
/Autofarmer/MouseKeyHook/HotKeys/HotKeySetsListener.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 |
--------------------------------------------------------------------------------
/Autofarmer/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Autofarmer/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/Callback.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using Gma.System.MouseKeyHook.WinApi;
6 |
7 | namespace Gma.System.MouseKeyHook.Implementation
8 | {
9 | internal delegate bool Callback(CallbackData data);
10 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/Subscribe.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using Gma.System.MouseKeyHook.WinApi;
6 |
7 | namespace Gma.System.MouseKeyHook.Implementation
8 | {
9 | internal delegate HookResult Subscribe(Callback callbck);
10 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/IKeyboardMouseEvents.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 |
7 | namespace Gma.System.MouseKeyHook
8 | {
9 | ///
10 | /// Provides keyboard and mouse events.
11 | ///
12 | public interface IKeyboardMouseEvents : IKeyboardEvents, IMouseEvents, IDisposable
13 | {
14 | }
15 | }
--------------------------------------------------------------------------------
/Autofarmer/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using System.Windows.Forms;
6 |
7 | namespace Autofarmer {
8 | static class Program {
9 | ///
10 | /// The main entry point for the application.
11 | ///
12 | [STAThread]
13 | static void Main() {
14 | Application.EnableVisualStyles();
15 | Application.SetCompatibleTextRenderingDefault(false);
16 | Application.Run(new Autofarm());
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/CallbackData.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 |
7 | namespace Gma.System.MouseKeyHook.WinApi
8 | {
9 | internal struct CallbackData
10 | {
11 | public CallbackData(IntPtr wParam, IntPtr lParam)
12 | {
13 | WParam = wParam;
14 | LParam = lParam;
15 | }
16 |
17 | public IntPtr WParam { get; }
18 |
19 | public IntPtr LParam { get; }
20 | }
21 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/AppEventFacade.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | namespace Gma.System.MouseKeyHook.Implementation
6 | {
7 | internal class AppEventFacade : EventFacade
8 | {
9 | protected override MouseListener CreateMouseListener()
10 | {
11 | return new AppMouseListener();
12 | }
13 |
14 | protected override KeyListener CreateKeyListener()
15 | {
16 | return new AppKeyListener();
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/GlobalEventFacade.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | namespace Gma.System.MouseKeyHook.Implementation
6 | {
7 | internal class GlobalEventFacade : EventFacade
8 | {
9 | protected override MouseListener CreateMouseListener()
10 | {
11 | return new GlobalMouseListener();
12 | }
13 |
14 | protected override KeyListener CreateKeyListener()
15 | {
16 | return new GlobalKeyListener();
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Reflection;
6 | using System.Runtime.InteropServices;
7 |
8 | [assembly: AssemblyTitle("MouseKeyHook")]
9 | [assembly:
10 | AssemblyDescription(
11 | "This library allows you to tap keyboard and mouse, to detect and record their activity even when an application is inactive and runs in background."
12 | )]
13 | [assembly: AssemblyCopyright("(c) George Mamaladze 2000-2018")]
14 | [assembly: ComVisible(false)]
15 | [assembly: AssemblyVersion("5.6.0")]
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/AppMouseListener.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using Gma.System.MouseKeyHook.WinApi;
6 |
7 | namespace Gma.System.MouseKeyHook.Implementation
8 | {
9 | internal class AppMouseListener : MouseListener
10 | {
11 | public AppMouseListener()
12 | : base(HookHelper.HookAppMouse)
13 | {
14 | }
15 |
16 | protected override MouseEventExtArgs GetEventArgs(CallbackData data)
17 | {
18 | return MouseEventExtArgs.FromRawDataApp(data);
19 | }
20 | }
21 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/HookResult.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 |
7 | namespace Gma.System.MouseKeyHook.WinApi
8 | {
9 | internal class HookResult : IDisposable
10 | {
11 | public HookResult(HookProcedureHandle handle, HookProcedure procedure)
12 | {
13 | Handle = handle;
14 | Procedure = procedure;
15 | }
16 |
17 | public HookProcedureHandle Handle { get; }
18 |
19 | public HookProcedure Procedure { get; }
20 |
21 | public void Dispose()
22 | {
23 | Handle.Dispose();
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/BaseListener.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using Gma.System.MouseKeyHook.WinApi;
7 |
8 | namespace Gma.System.MouseKeyHook.Implementation
9 | {
10 | internal abstract class BaseListener : IDisposable
11 | {
12 | protected BaseListener(Subscribe subscribe)
13 | {
14 | Handle = subscribe(Callback);
15 | }
16 |
17 | protected HookResult Handle { get; set; }
18 |
19 | public void Dispose()
20 | {
21 | Handle.Dispose();
22 | }
23 |
24 | protected abstract bool Callback(CallbackData data);
25 | }
26 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/ButtonSet.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Windows.Forms;
6 |
7 | namespace Gma.System.MouseKeyHook.Implementation
8 | {
9 | internal class ButtonSet
10 | {
11 | private MouseButtons m_Set;
12 |
13 | public ButtonSet()
14 | {
15 | m_Set = MouseButtons.None;
16 | }
17 |
18 | public void Add(MouseButtons element)
19 | {
20 | m_Set |= element;
21 | }
22 |
23 | public void Remove(MouseButtons element)
24 | {
25 | m_Set &= ~element;
26 | }
27 |
28 | public bool Contains(MouseButtons element)
29 | {
30 | return (m_Set & element) != MouseButtons.None;
31 | }
32 | }
33 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/KeysExtensions.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2010-2018 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Windows.Forms;
6 |
7 | namespace Gma.System.MouseKeyHook.Implementation
8 | {
9 | internal static class KeysExtensions
10 | {
11 | public static Keys Normalize(this Keys key)
12 | {
13 | if ((key & Keys.LControlKey) == Keys.LControlKey ||
14 | (key & Keys.RControlKey) == Keys.RControlKey) return Keys.Control;
15 | if ((key & Keys.LShiftKey) == Keys.LShiftKey ||
16 | (key & Keys.RShiftKey) == Keys.RShiftKey) return Keys.Shift;
17 | if ((key & Keys.LMenu) == Keys.LMenu ||
18 | (key & Keys.RMenu) == Keys.RMenu) return Keys.Alt;
19 | return key;
20 | }
21 | }
22 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/AppKeyListener.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Collections.Generic;
6 | using Gma.System.MouseKeyHook.WinApi;
7 |
8 | namespace Gma.System.MouseKeyHook.Implementation
9 | {
10 | internal class AppKeyListener : KeyListener
11 | {
12 | public AppKeyListener()
13 | : base(HookHelper.HookAppKeyboard)
14 | {
15 | }
16 |
17 | protected override IEnumerable GetPressEventArgs(CallbackData data)
18 | {
19 | return KeyPressEventArgsExt.FromRawDataApp(data);
20 | }
21 |
22 | protected override KeyEventArgsExt GetDownUpEventArgs(CallbackData data)
23 | {
24 | return KeyEventArgsExt.FromRawDataApp(data);
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/GlobalKeyListener.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Collections.Generic;
6 | using Gma.System.MouseKeyHook.WinApi;
7 |
8 | namespace Gma.System.MouseKeyHook.Implementation
9 | {
10 | internal class GlobalKeyListener : KeyListener
11 | {
12 | public GlobalKeyListener()
13 | : base(HookHelper.HookGlobalKeyboard)
14 | {
15 | }
16 |
17 | protected override IEnumerable GetPressEventArgs(CallbackData data)
18 | {
19 | return KeyPressEventArgsExt.FromRawDataGlobal(data);
20 | }
21 |
22 | protected override KeyEventArgsExt GetDownUpEventArgs(CallbackData data)
23 | {
24 | return KeyEventArgsExt.FromRawDataGlobal(data);
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/HotKeys/HotKeyArgs.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 |
7 | namespace Gma.System.MouseKeyHook.HotKeys
8 | {
9 | ///
10 | /// The event arguments passed when a HotKeySet's OnHotKeysDownHold event is triggered.
11 | ///
12 | public sealed class HotKeyArgs : EventArgs
13 | {
14 | ///
15 | /// Creates an instance of the HotKeyArgs.
16 | /// Time when the event was triggered
17 | ///
18 | public HotKeyArgs(DateTime triggeredAt)
19 | {
20 | Time = triggeredAt;
21 | }
22 |
23 | ///
24 | /// Time when the event was triggered
25 | ///
26 | public DateTime Time { get; }
27 | }
28 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/HookProcedureHandle.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Windows.Forms;
6 | using Microsoft.Win32.SafeHandles;
7 |
8 | namespace Gma.System.MouseKeyHook.WinApi
9 | {
10 | internal class HookProcedureHandle : SafeHandleZeroOrMinusOneIsInvalid
11 | {
12 | private static bool _closing;
13 |
14 | static HookProcedureHandle()
15 | {
16 | Application.ApplicationExit += (sender, e) => { _closing = true; };
17 | }
18 |
19 | public HookProcedureHandle()
20 | : base(true)
21 | {
22 | }
23 |
24 | protected override bool ReleaseHandle()
25 | {
26 | //NOTE Calling Unhook during processexit causes deley
27 | if (_closing) return true;
28 | return HookNativeMethods.UnhookWindowsHookEx(handle) != 0;
29 | }
30 | }
31 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2018 Blacklock
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/Autofarmer/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace Autofarmer.Properties {
12 |
13 |
14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
17 |
18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
19 |
20 | public static Settings Default {
21 | get {
22 | return defaultInstance;
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/MouseNativeMethods.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Runtime.InteropServices;
6 |
7 | namespace Gma.System.MouseKeyHook.WinApi
8 | {
9 | internal static class MouseNativeMethods
10 | {
11 | ///
12 | /// The GetDoubleClickTime function retrieves the current double-click time for the mouse. A double-click is a series
13 | /// of two clicks of the
14 | /// mouse button, the second occurring within a specified time after the first. The double-click time is the maximum
15 | /// number of
16 | /// milliseconds that may occur between the first and second click of a double-click.
17 | ///
18 | ///
19 | /// The return value specifies the current double-click time, in milliseconds.
20 | ///
21 | ///
22 | /// http://msdn.microsoft.com/en-us/library/ms646258(VS.85).aspx
23 | ///
24 | [DllImport("user32")]
25 | internal static extern int GetDoubleClickTime();
26 | }
27 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/HookIds.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | namespace Gma.System.MouseKeyHook.WinApi
6 | {
7 | internal static class HookIds
8 | {
9 | ///
10 | /// Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
11 | ///
12 | internal const int WH_MOUSE = 7;
13 |
14 | ///
15 | /// Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook
16 | /// procedure.
17 | ///
18 | internal const int WH_KEYBOARD = 2;
19 |
20 | ///
21 | /// Windows NT/2000/XP/Vista/7: Installs a hook procedure that monitors low-level mouse input events.
22 | ///
23 | internal const int WH_MOUSE_LL = 14;
24 |
25 | ///
26 | /// Windows NT/2000/XP/Vista/7: Installs a hook procedure that monitors low-level keyboard input events.
27 | ///
28 | internal const int WH_KEYBOARD_LL = 13;
29 | }
30 | }
--------------------------------------------------------------------------------
/Autofarmer.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 14
4 | VisualStudioVersion = 14.0.23107.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Autofarmer", "Autofarmer\Autofarmer.csproj", "{55F3DB6F-FA3A-493D-8FDC-88404C7CC89D}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{7C312F5F-950A-462B-B881-4FA605C727C6}"
9 | ProjectSection(SolutionItems) = preProject
10 | KeyboardHook.cs = KeyboardHook.cs
11 | MouseHook.cs = MouseHook.cs
12 | EndProjectSection
13 | EndProject
14 | Global
15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
16 | Debug|Any CPU = Debug|Any CPU
17 | Release|Any CPU = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
20 | {55F3DB6F-FA3A-493D-8FDC-88404C7CC89D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {55F3DB6F-FA3A-493D-8FDC-88404C7CC89D}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {55F3DB6F-FA3A-493D-8FDC-88404C7CC89D}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {55F3DB6F-FA3A-493D-8FDC-88404C7CC89D}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | EndGlobal
29 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Hook.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using Gma.System.MouseKeyHook.Implementation;
6 |
7 | namespace Gma.System.MouseKeyHook
8 | {
9 | ///
10 | /// This is the class to start with.
11 | ///
12 | public static class Hook
13 | {
14 | ///
15 | /// Here you find all application wide events. Both mouse and keyboard.
16 | ///
17 | ///
18 | /// Returned instance is used for event subscriptions.
19 | /// You can refetch it (you will get the same instance anyway).
20 | ///
21 | public static IKeyboardMouseEvents AppEvents()
22 | {
23 | return new AppEventFacade();
24 | }
25 |
26 | ///
27 | /// Here you find all application wide events. Both mouse and keyboard.
28 | ///
29 | ///
30 | /// Returned instance is used for event subscriptions.
31 | /// You can refetch it (you will get the same instance anyway).
32 | ///
33 | public static IKeyboardMouseEvents GlobalEvents()
34 | {
35 | return new GlobalEventFacade();
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/Autofarmer/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("Autofarmer")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("Autofarmer")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("55f3db6f-fa3a-493d-8fdc-88404c7cc89d")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/HotKeys/HotKeySetCollection.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Collections.Generic;
6 |
7 | namespace Gma.System.MouseKeyHook.HotKeys
8 | {
9 | ///
10 | /// A collection of HotKeySets
11 | ///
12 | public sealed class HotKeySetCollection : List
13 | {
14 | private KeyChainHandler m_keyChain;
15 |
16 | ///
17 | /// Adds a HotKeySet to the collection.
18 | ///
19 | ///
20 | public new void Add(HotKeySet hks)
21 | {
22 | m_keyChain += hks.OnKey;
23 | base.Add(hks);
24 | }
25 |
26 | ///
27 | /// Removes the HotKeySet from the collection.
28 | ///
29 | ///
30 | public new void Remove(HotKeySet hks)
31 | {
32 | m_keyChain -= hks.OnKey;
33 | base.Remove(hks);
34 | }
35 |
36 | ///
37 | /// Uses a multi-case delegate to invoke individual HotKeySets if the Key is in use by any HotKeySets.
38 | ///
39 | ///
40 | internal void OnKey(KeyEventArgsExt e)
41 | {
42 | if (m_keyChain != null)
43 | m_keyChain(e);
44 | }
45 |
46 | private delegate void KeyChainHandler(KeyEventArgsExt kex);
47 | }
48 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/MouseKeyHook.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | MouseKeyHook
6 | 5.6.1-alpha
7 | $title$
8 | George Mamaladze
9 | George Mamaladze
10 | https://github.com/gmamaladze/globalmousekeyhook/blob/master/LICENSE.txt
11 | https://github.com/gmamaladze/globalmousekeyhook
12 | false
13 |
14 | This library attaches to windows global hooks, tracks keyboard and mouse clicks and movement and raises common .NET events with KeyEventArgs and MouseEventArgs, so you can easily retrieve any information you need:
15 |
16 | * Mouse coordinates
17 | * Mouse buttons clicked
18 | * Mouse wheel scrolls
19 | * Key presses and releases
20 | * Special key states
21 | * [NEW] Key combinations and sequences
22 |
23 | Additionally, there is a possibility to supress certain keyboard or mouse clicks, or detect special key combinations.
24 |
25 | This library allows you to tap keyboard and mouse, to detect and record their activity even when an application is inactive and runs in background.
26 | (c) George Mamaladze 2000-2018
27 | keyboard mouse hook event global spy
28 | https://raw.githubusercontent.com/gmamaladze/globalmousekeyhook/master/mouse-keyboard-hook-logo64x64.png
29 |
30 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Sequence.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2010-2018 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Linq;
6 |
7 | namespace Gma.System.MouseKeyHook
8 | {
9 | ///
10 | /// Describes key or key combination sequences. e.g. Control+Z,Z
11 | ///
12 | public class Sequence : SequenceBase
13 | {
14 | private Sequence(Combination[] combinations) : base(combinations)
15 | {
16 | }
17 |
18 | ///
19 | /// Creates an instance of sequence object from parameters representing keys or key combinations.
20 | ///
21 | ///
22 | ///
23 | public static Sequence Of(params Combination[] combinations)
24 | {
25 | return new Sequence(combinations);
26 | }
27 |
28 | ///
29 | /// Creates an instance of sequnce object from string.
30 | /// The string must contain comma ',' delimited list of strings describing keys or key combinations.
31 | /// Examples: 'A,B,C' 'Alt+R,S', 'Shift+R,Alt+K'
32 | ///
33 | ///
34 | ///
35 | public static Sequence FromString(string text)
36 | {
37 | var parts = text.Split(',');
38 | var combinations = parts.Select(Combination.FromString).ToArray();
39 | return new Sequence(combinations);
40 | }
41 | }
42 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/KeyboardHookStruct.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Runtime.InteropServices;
6 |
7 | namespace Gma.System.MouseKeyHook.WinApi
8 | {
9 | ///
10 | /// The KeyboardHookStruct structure contains information about a low-level keyboard input event.
11 | ///
12 | ///
13 | /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp
14 | ///
15 | [StructLayout(LayoutKind.Sequential)]
16 | internal struct KeyboardHookStruct
17 | {
18 | ///
19 | /// Specifies a virtual-key code. The code must be a value in the range 1 to 254.
20 | ///
21 | public int VirtualKeyCode;
22 |
23 | ///
24 | /// Specifies a hardware scan code for the key.
25 | ///
26 | public int ScanCode;
27 |
28 | ///
29 | /// Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
30 | ///
31 | public int Flags;
32 |
33 | ///
34 | /// Specifies the Time stamp for this message.
35 | ///
36 | public int Time;
37 |
38 | ///
39 | /// Specifies extra information associated with the message.
40 | ///
41 | public int ExtraInfo;
42 | }
43 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/IKeyboardEvents.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Windows.Forms;
6 |
7 | namespace Gma.System.MouseKeyHook
8 | {
9 | ///
10 | /// Provides keyboard events
11 | ///
12 | public interface IKeyboardEvents
13 | {
14 | ///
15 | /// Occurs when a key is pressed.
16 | ///
17 | event KeyEventHandler KeyDown;
18 |
19 | ///
20 | /// Occurs when a key is pressed.
21 | ///
22 | ///
23 | /// Key events occur in the following order:
24 | ///
25 | /// - KeyDown
26 | /// - KeyPress
27 | /// - KeyUp
28 | ///
29 | /// The KeyPress event is not raised by non-character keys; however, the non-character keys do raise the KeyDown and
30 | /// KeyUp events.
31 | /// Use the KeyChar property to sample keystrokes at run time and to consume or modify a subset of common keystrokes.
32 | /// To handle keyboard events only in your application and not enable other applications to receive keyboard events,
33 | /// set the property in your form's KeyPress event-handling method to
34 | /// true.
35 | ///
36 | event KeyPressEventHandler KeyPress;
37 |
38 | ///
39 | /// Occurs when a key is released.
40 | ///
41 | event KeyEventHandler KeyUp;
42 | }
43 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # GTAutofarmer (abandoned)
2 |
3 | **This project is unfinished & has been abandoned. There are better autofarmers out there nowadays, go use one of those instead. It is also apparently now detectable by the anticheat.**
4 |
5 | ## Media
6 |
7 | 
8 |
9 | 
10 |
11 | 
12 |
13 | ## How it ~~works~~ worked
14 |
15 | Growtopia uses a mutant handle called `\Sessions\1\BaseNamedObjects\Growtopia` which prevents us from opening more than one instance of the game at a time. To circumvent that, we first suspend all the instances of the game (since it'll crash if we just attempt to delete the handles), and only then delete the handles and open a new game.
16 |
17 | ### Details
18 |
19 | When a new instance of Growtopia.exe is launched, we first suspend all other instances of the game using `SuspendThread`.
20 | Then we get all the handles in the system with `NtQuerySystemInformation` and filter out those that are not owned by the latest Growtopia process). We get the names of the remaining handles by duplicating them with `DuplicateHandle` so that we can retrieve information out of them with `NtQueryObject`.
21 |
22 | Then we filter out handles with incorrect names and end up with the handles that we have to delete.
23 | To do that, we use `DuplicateHandle` with `DUPLICATE_CLOSE_SOURCE` and specify no process to duplicate to.
24 |
25 | Once all the handles are deleted, we launch a new Growtopia process, which will create new handles. Now we resume all the other
26 | Growtopia.exe's with `ResumeThread` and we've ended up with one new Growtopia instance open.
27 |
28 | ## License
29 |
30 | This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
31 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/Point.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Runtime.InteropServices;
6 |
7 | namespace Gma.System.MouseKeyHook.WinApi
8 | {
9 | ///
10 | /// The Point structure defines the X- and Y- coordinates of a point.
11 | ///
12 | ///
13 | /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/rectangl_0tiq.asp
14 | ///
15 | [StructLayout(LayoutKind.Sequential)]
16 | internal struct Point
17 | {
18 | ///
19 | /// Specifies the X-coordinate of the point.
20 | ///
21 | public int X;
22 |
23 | ///
24 | /// Specifies the Y-coordinate of the point.
25 | ///
26 | public int Y;
27 |
28 | public Point(int x, int y)
29 | {
30 | X = x;
31 | Y = y;
32 | }
33 |
34 | public static bool operator ==(Point a, Point b)
35 | {
36 | return a.X == b.X && a.Y == b.Y;
37 | }
38 |
39 | public static bool operator !=(Point a, Point b)
40 | {
41 | return !(a == b);
42 | }
43 |
44 | public bool Equals(Point other)
45 | {
46 | return other.X == X && other.Y == Y;
47 | }
48 |
49 | public override bool Equals(object obj)
50 | {
51 | if (ReferenceEquals(null, obj)) return false;
52 | if (obj.GetType() != typeof(Point)) return false;
53 | return Equals((Point) obj);
54 | }
55 |
56 | public override int GetHashCode()
57 | {
58 | unchecked
59 | {
60 | return (X * 397) ^ Y;
61 | }
62 | }
63 | }
64 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/ThreadNativeMethods.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 |
8 | namespace Gma.System.MouseKeyHook.WinApi
9 | {
10 | internal static class ThreadNativeMethods
11 | {
12 | ///
13 | /// Retrieves the unmanaged thread identifier of the calling thread.
14 | ///
15 | ///
16 | [DllImport("kernel32")]
17 | internal static extern int GetCurrentThreadId();
18 |
19 | ///
20 | /// Retrieves a handle to the foreground window (the window with which the user is currently working).
21 | /// The system assigns a slightly higher priority to the thread that creates the foreground window than it does to
22 | /// other threads.
23 | ///
24 | ///
25 | [DllImport("user32.dll", CharSet = CharSet.Auto)]
26 | internal static extern IntPtr GetForegroundWindow();
27 |
28 | ///
29 | /// Retrieves the identifier of the thread that created the specified window and, optionally, the identifier of the
30 | /// process that
31 | /// created the window.
32 | ///
33 | /// A handle to the window.
34 | ///
35 | /// A pointer to a variable that receives the process identifier. If this parameter is not NULL,
36 | /// GetWindowThreadProcessId copies the identifier of the process to the variable; otherwise, it does not.
37 | ///
38 | /// The return value is the identifier of the thread that created the window.
39 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
40 | internal static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
41 | }
42 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/MouseStruct.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Runtime.InteropServices;
6 |
7 | namespace Gma.System.MouseKeyHook.WinApi
8 | {
9 | ///
10 | /// The structure contains information about a mouse input event.
11 | ///
12 | ///
13 | /// See full documentation at http://globalmousekeyhook.codeplex.com/wikipage?title=MouseStruct
14 | ///
15 | [StructLayout(LayoutKind.Explicit)]
16 | internal struct MouseStruct
17 | {
18 | ///
19 | /// Specifies a Point structure that contains the X- and Y-coordinates of the cursor, in screen coordinates.
20 | ///
21 | [FieldOffset(0x00)] public Point Point;
22 |
23 | ///
24 | /// Specifies information associated with the message.
25 | ///
26 | ///
27 | /// The possible values are:
28 | ///
29 | /// -
30 | /// 0 - No Information
31 | ///
32 | /// -
33 | /// 1 - X-Button1 Click
34 | ///
35 | /// -
36 | /// 2 - X-Button2 Click
37 | ///
38 | /// -
39 | /// 120 - Mouse Scroll Away from User
40 | ///
41 | /// -
42 | /// -120 - Mouse Scroll Toward User
43 | ///
44 | ///
45 | ///
46 | [FieldOffset(0x0A)] public short MouseData;
47 |
48 | ///
49 | /// Returns a Timestamp associated with the input, in System Ticks.
50 | ///
51 | [FieldOffset(0x10)] public int Timestamp;
52 | }
53 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/KeyListener.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Collections.Generic;
6 | using System.Windows.Forms;
7 | using Gma.System.MouseKeyHook.WinApi;
8 |
9 | namespace Gma.System.MouseKeyHook.Implementation
10 | {
11 | internal abstract class KeyListener : BaseListener, IKeyboardEvents
12 | {
13 | protected KeyListener(Subscribe subscribe)
14 | : base(subscribe)
15 | {
16 | }
17 |
18 | public event KeyEventHandler KeyDown;
19 | public event KeyPressEventHandler KeyPress;
20 | public event KeyEventHandler KeyUp;
21 |
22 | public void InvokeKeyDown(KeyEventArgsExt e)
23 | {
24 | var handler = KeyDown;
25 | if (handler == null || e.Handled || !e.IsKeyDown)
26 | return;
27 | handler(this, e);
28 | }
29 |
30 | public void InvokeKeyPress(KeyPressEventArgsExt e)
31 | {
32 | var handler = KeyPress;
33 | if (handler == null || e.Handled || e.IsNonChar)
34 | return;
35 | handler(this, e);
36 | }
37 |
38 | public void InvokeKeyUp(KeyEventArgsExt e)
39 | {
40 | var handler = KeyUp;
41 | if (handler == null || e.Handled || !e.IsKeyUp)
42 | return;
43 | handler(this, e);
44 | }
45 |
46 | protected override bool Callback(CallbackData data)
47 | {
48 | var eDownUp = GetDownUpEventArgs(data);
49 |
50 | InvokeKeyDown(eDownUp);
51 |
52 | if (KeyPress != null)
53 | {
54 | var pressEventArgs = GetPressEventArgs(data);
55 | foreach (var pressEventArg in pressEventArgs)
56 | InvokeKeyPress(pressEventArg);
57 | }
58 |
59 | InvokeKeyUp(eDownUp);
60 |
61 | return !eDownUp.Handled;
62 | }
63 |
64 | protected abstract IEnumerable GetPressEventArgs(CallbackData data);
65 | protected abstract KeyEventArgsExt GetDownUpEventArgs(CallbackData data);
66 | }
67 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/HookProcedure.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 |
7 | namespace Gma.System.MouseKeyHook.WinApi
8 | {
9 | ///
10 | /// The CallWndProc hook procedure is an application-defined or library-defined callback
11 | /// function used with the SetWindowsHookEx function. The HOOKPROC type defines a pointer
12 | /// to this callback function. CallWndProc is a placeholder for the application-defined
13 | /// or library-defined function name.
14 | ///
15 | ///
16 | /// [in] Specifies whether the hook procedure must process the message.
17 | /// If nCode is HC_ACTION, the hook procedure must process the message.
18 | /// If nCode is less than zero, the hook procedure must pass the message to the
19 | /// CallNextHookEx function without further processing and must return the
20 | /// value returned by CallNextHookEx.
21 | ///
22 | ///
23 | /// [in] Specifies whether the message was sent by the current thread.
24 | /// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
25 | ///
26 | ///
27 | /// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
28 | ///
29 | ///
30 | /// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
31 | /// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
32 | /// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
33 | /// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
34 | /// procedure does not call CallNextHookEx, the return value should be zero.
35 | ///
36 | ///
37 | /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/callwndproc.asp
38 | ///
39 | public delegate IntPtr HookProcedure(int nCode, IntPtr wParam, IntPtr lParam);
40 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/Chord.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2010-2018 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Collections;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using System.Windows.Forms;
10 |
11 | namespace Gma.System.MouseKeyHook.Implementation
12 | {
13 | internal class Chord : IEnumerable
14 | {
15 | private readonly Keys[] _keys;
16 |
17 | internal Chord(IEnumerable additionalKeys)
18 | {
19 | _keys = additionalKeys.Select(k => k.Normalize()).OrderBy(k => k).ToArray();
20 | }
21 |
22 | public int Count
23 | {
24 | get { return _keys.Length; }
25 | }
26 |
27 | public IEnumerator GetEnumerator()
28 | {
29 | return _keys.Cast().GetEnumerator();
30 | }
31 |
32 | IEnumerator IEnumerable.GetEnumerator()
33 | {
34 | return GetEnumerator();
35 | }
36 |
37 | public override string ToString()
38 | {
39 | return string.Join("+", _keys);
40 | }
41 |
42 | public static Chord FromString(string chord)
43 | {
44 | var parts = chord
45 | .Split('+')
46 | .Select(p => Enum.Parse(typeof(Keys), p))
47 | .Cast();
48 | var stack = new Stack(parts);
49 | return new Chord(stack);
50 | }
51 |
52 | protected bool Equals(Chord other)
53 | {
54 | if (_keys.Length != other._keys.Length) return false;
55 | return _keys.SequenceEqual(other._keys);
56 | }
57 |
58 | public override bool Equals(object obj)
59 | {
60 | if (ReferenceEquals(null, obj)) return false;
61 | if (ReferenceEquals(this, obj)) return true;
62 | if (obj.GetType() != GetType()) return false;
63 | return Equals((Chord) obj);
64 | }
65 |
66 | public override int GetHashCode()
67 | {
68 | unchecked
69 | {
70 | return (_keys.Length + 13) ^
71 | ((_keys.Length != 0 ? (int) _keys[0] ^ (int) _keys[_keys.Length - 1] : 0) * 397);
72 | }
73 | }
74 | }
75 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/GlobalMouseListener.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Windows.Forms;
6 | using Gma.System.MouseKeyHook.WinApi;
7 |
8 | namespace Gma.System.MouseKeyHook.Implementation
9 | {
10 | internal class GlobalMouseListener : MouseListener
11 | {
12 | private readonly int m_SystemDoubleClickTime;
13 | private MouseButtons m_PreviousClicked;
14 | private Point m_PreviousClickedPosition;
15 | private int m_PreviousClickedTime;
16 |
17 | public GlobalMouseListener()
18 | : base(HookHelper.HookGlobalMouse)
19 | {
20 | m_SystemDoubleClickTime = MouseNativeMethods.GetDoubleClickTime();
21 | }
22 |
23 | protected override void ProcessDown(ref MouseEventExtArgs e)
24 | {
25 | if (IsDoubleClick(e))
26 | e = e.ToDoubleClickEventArgs();
27 | base.ProcessDown(ref e);
28 | }
29 |
30 | protected override void ProcessUp(ref MouseEventExtArgs e)
31 | {
32 | base.ProcessUp(ref e);
33 | if (e.Clicks == 2)
34 | StopDoubleClickWaiting();
35 |
36 | if (e.Clicks == 1)
37 | StartDoubleClickWaiting(e);
38 | }
39 |
40 | private void StartDoubleClickWaiting(MouseEventExtArgs e)
41 | {
42 | m_PreviousClicked = e.Button;
43 | m_PreviousClickedTime = e.Timestamp;
44 | m_PreviousClickedPosition = e.Point;
45 | }
46 |
47 | private void StopDoubleClickWaiting()
48 | {
49 | m_PreviousClicked = MouseButtons.None;
50 | m_PreviousClickedTime = 0;
51 | m_PreviousClickedPosition = new Point(0, 0);
52 | }
53 |
54 | private bool IsDoubleClick(MouseEventExtArgs e)
55 | {
56 | return
57 | e.Button == m_PreviousClicked &&
58 | e.Point == m_PreviousClickedPosition && // Click-move-click exception, see Patch 11222
59 | e.Timestamp - m_PreviousClickedTime <= m_SystemDoubleClickTime;
60 | }
61 |
62 | protected override MouseEventExtArgs GetEventArgs(CallbackData data)
63 | {
64 | return MouseEventExtArgs.FromRawDataGlobal(data);
65 | }
66 | }
67 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/SequenceBase.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2010-2018 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System.Collections;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 |
9 | namespace Gma.System.MouseKeyHook
10 | {
11 | ///
12 | /// Describes a sequence of generic objects.
13 | ///
14 | ///
15 | public abstract class SequenceBase : IEnumerable
16 | {
17 | private readonly T[] _elements;
18 |
19 | ///
20 | /// Creates an instance of sequnce from sequnce elements.
21 | ///
22 | ///
23 | protected SequenceBase(params T[] elements)
24 | {
25 | _elements = elements;
26 | }
27 |
28 | ///
29 | /// Number of elements in the sequnce.
30 | ///
31 | public int Length
32 | {
33 | get { return _elements.Length; }
34 | }
35 |
36 | ///
37 | public IEnumerator GetEnumerator()
38 | {
39 | return _elements.Cast().GetEnumerator();
40 | }
41 |
42 | ///
43 | IEnumerator IEnumerable.GetEnumerator()
44 | {
45 | return GetEnumerator();
46 | }
47 |
48 | ///
49 | public override string ToString()
50 | {
51 | return string.Join(",", _elements);
52 | }
53 |
54 | ///
55 | protected bool Equals(SequenceBase other)
56 | {
57 | if (_elements.Length != other._elements.Length) return false;
58 | return _elements.SequenceEqual(other._elements);
59 | }
60 |
61 | ///
62 | public override bool Equals(object obj)
63 | {
64 | if (ReferenceEquals(null, obj)) return false;
65 | if (ReferenceEquals(this, obj)) return true;
66 | if (obj.GetType() != GetType()) return false;
67 | return Equals((Combination) obj);
68 | }
69 |
70 | ///
71 | public override int GetHashCode()
72 | {
73 | unchecked
74 | {
75 | return (_elements.Length + 13) ^
76 | ((_elements.Length != 0
77 | ? _elements[0].GetHashCode() ^ _elements[_elements.Length - 1].GetHashCode()
78 | : 0) * 397);
79 | }
80 | }
81 | }
82 | }
--------------------------------------------------------------------------------
/Autofarmer/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace Autofarmer.Properties {
12 |
13 |
14 | ///
15 | /// A strongly-typed resource class, for looking up localized strings, etc.
16 | ///
17 | // This class was auto-generated by the StronglyTypedResourceBuilder
18 | // class via a tool like ResGen or Visual Studio.
19 | // To add or remove a member, edit your .ResX file then rerun ResGen
20 | // with the /str option, or rebuild your VS project.
21 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
22 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
23 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
24 | internal class Resources {
25 |
26 | private static global::System.Resources.ResourceManager resourceMan;
27 |
28 | private static global::System.Globalization.CultureInfo resourceCulture;
29 |
30 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
31 | internal Resources() {
32 | }
33 |
34 | ///
35 | /// Returns the cached ResourceManager instance used by this class.
36 | ///
37 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
38 | internal static global::System.Resources.ResourceManager ResourceManager {
39 | get {
40 | if ((resourceMan == null)) {
41 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Autofarmer.Properties.Resources", typeof(Resources).Assembly);
42 | resourceMan = temp;
43 | }
44 | return resourceMan;
45 | }
46 | }
47 |
48 | ///
49 | /// Overrides the current thread's CurrentUICulture property for all
50 | /// resource lookups using this strongly typed resource class.
51 | ///
52 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
53 | internal static global::System.Globalization.CultureInfo Culture {
54 | get {
55 | return resourceCulture;
56 | }
57 | set {
58 | resourceCulture = value;
59 | }
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/HotkeysNativeMethods.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace Gma.System.MouseKeyHook.WinApi
5 | {
6 | internal static class HotkeysNativeMethods
7 | {
8 | ///
9 | /// Defines a system-wide hot key.
10 | ///
11 | ///
12 | /// A handle to the window that will receive WM_HOTKEY messages generated by the hot key. If this parameter is NULL,
13 | /// WM_HOTKEY messages are posted to the message queue of the calling thread and must be processed in the message loop.
14 | ///
15 | ///
16 | /// The identifier of the hot key. If the hWnd parameter is NULL, then the hot key is associated with the current
17 | /// thread rather than with a particular window. If a hot key already exists with the same hWnd and id parameters, see
18 | /// Remarks for the action taken.
19 | ///
20 | ///
21 | /// The keys that must be pressed in combination with the key specified by the uVirtKey parameter in order to generate
22 | /// the WM_HOTKEY message. The fsModifiers parameter can be a combination of the following values.
23 | ///
24 | ///
25 | /// The virtual-key code of the hot key. See Virtual Key Codes.
26 | ///
27 | ///
28 | /// If the function succeeds, the return value is nonzero.
29 | /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
30 | ///
31 | [DllImport("user32.dll")]
32 | public static extern int RegisterHotKey(IntPtr hwnd, int id, int fsModifiers, int vk);
33 |
34 | ///
35 | /// Frees a hot key previously registered by the calling thread.
36 | ///
37 | ///
38 | /// A handle to the window associated with the hot key to be freed. This parameter should be NULL if the hot key is not
39 | /// associated with a window.
40 | ///
41 | ///
42 | /// The identifier of the hot key to be freed.
43 | ///
44 | ///
45 | /// If the function succeeds, the return value is nonzero.
46 | /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
47 | ///
48 | [DllImport("user32.dll")]
49 | public static extern bool UnregisterHotKey(IntPtr hwnd, int id);
50 | }
51 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/AppMouseStruct.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 |
8 | namespace Gma.System.MouseKeyHook.WinApi
9 | {
10 | ///
11 | /// The AppMouseStruct structure contains information about a application-level mouse input event.
12 | ///
13 | ///
14 | /// See full documentation at http://globalmousekeyhook.codeplex.com/wikipage?title=MouseStruct
15 | ///
16 | [StructLayout(LayoutKind.Explicit)]
17 | internal struct AppMouseStruct
18 | {
19 | ///
20 | /// Specifies a Point structure that contains the X- and Y-coordinates of the cursor, in screen coordinates.
21 | ///
22 | [FieldOffset(0x00)] public Point Point;
23 |
24 | ///
25 | /// Specifies information associated with the message.
26 | ///
27 | ///
28 | /// The possible values are:
29 | ///
30 | /// -
31 | /// 0 - No Information
32 | ///
33 | /// -
34 | /// 1 - X-Button1 Click
35 | ///
36 | /// -
37 | /// 2 - X-Button2 Click
38 | ///
39 | /// -
40 | /// 120 - Mouse Scroll Away from User
41 | ///
42 | /// -
43 | /// -120 - Mouse Scroll Toward User
44 | ///
45 | ///
46 | ///
47 | [FieldOffset(0x16)] public short MouseData_x86;
48 |
49 | [FieldOffset(0x22)] public short MouseData_x64;
50 |
51 | ///
52 | /// Converts the current into a .
53 | ///
54 | ///
55 | ///
56 | /// The AppMouseStruct does not have a timestamp, thus one is generated at the time of this call.
57 | ///
58 | public MouseStruct ToMouseStruct()
59 | {
60 | var tmp = new MouseStruct();
61 | tmp.Point = Point;
62 | tmp.MouseData = IntPtr.Size == 4 ? MouseData_x86 : MouseData_x64;
63 | tmp.Timestamp = Environment.TickCount;
64 | return tmp;
65 | }
66 | }
67 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/HookHelper.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.ComponentModel;
7 | using System.Diagnostics;
8 | using System.Runtime.InteropServices;
9 | using Gma.System.MouseKeyHook.Implementation;
10 |
11 | namespace Gma.System.MouseKeyHook.WinApi
12 | {
13 | internal static class HookHelper
14 | {
15 | private static HookProcedure _appHookProc;
16 | private static HookProcedure _globalHookProc;
17 |
18 | public static HookResult HookAppMouse(Callback callback)
19 | {
20 | return HookApp(HookIds.WH_MOUSE, callback);
21 | }
22 |
23 | public static HookResult HookAppKeyboard(Callback callback)
24 | {
25 | return HookApp(HookIds.WH_KEYBOARD, callback);
26 | }
27 |
28 | public static HookResult HookGlobalMouse(Callback callback)
29 | {
30 | return HookGlobal(HookIds.WH_MOUSE_LL, callback);
31 | }
32 |
33 | public static HookResult HookGlobalKeyboard(Callback callback)
34 | {
35 | return HookGlobal(HookIds.WH_KEYBOARD_LL, callback);
36 | }
37 |
38 | private static HookResult HookApp(int hookId, Callback callback)
39 | {
40 | _appHookProc = (code, param, lParam) => HookProcedure(code, param, lParam, callback);
41 |
42 | var hookHandle = HookNativeMethods.SetWindowsHookEx(
43 | hookId,
44 | _appHookProc,
45 | IntPtr.Zero,
46 | ThreadNativeMethods.GetCurrentThreadId());
47 |
48 | if (hookHandle.IsInvalid)
49 | ThrowLastUnmanagedErrorAsException();
50 |
51 | return new HookResult(hookHandle, _appHookProc);
52 | }
53 |
54 | private static HookResult HookGlobal(int hookId, Callback callback)
55 | {
56 | _globalHookProc = (code, param, lParam) => HookProcedure(code, param, lParam, callback);
57 |
58 | var hookHandle = HookNativeMethods.SetWindowsHookEx(
59 | hookId,
60 | _globalHookProc,
61 | Process.GetCurrentProcess().MainModule.BaseAddress,
62 | 0);
63 |
64 | if (hookHandle.IsInvalid)
65 | ThrowLastUnmanagedErrorAsException();
66 |
67 | return new HookResult(hookHandle, _globalHookProc);
68 | }
69 |
70 | private static IntPtr HookProcedure(int nCode, IntPtr wParam, IntPtr lParam, Callback callback)
71 | {
72 | var passThrough = nCode != 0;
73 | if (passThrough)
74 | return CallNextHookEx(nCode, wParam, lParam);
75 |
76 | var callbackData = new CallbackData(wParam, lParam);
77 | var continueProcessing = callback(callbackData);
78 |
79 | if (!continueProcessing)
80 | return new IntPtr(-1);
81 |
82 | return CallNextHookEx(nCode, wParam, lParam);
83 | }
84 |
85 | private static IntPtr CallNextHookEx(int nCode, IntPtr wParam, IntPtr lParam)
86 | {
87 | return HookNativeMethods.CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
88 | }
89 |
90 | private static void ThrowLastUnmanagedErrorAsException()
91 | {
92 | var errorCode = Marshal.GetLastWin32Error();
93 | throw new Win32Exception(errorCode);
94 | }
95 | }
96 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/HotKeys/ReadMe.txt:
--------------------------------------------------------------------------------
1 | Until a separate, full-featured test version is ready, here's a quick update that can be made to the TestFormHookListeners:
2 |
3 | //HotKeySetsListener inherits KeyboardHookListener
4 | private readonly HotKeySetsListener m_KeyboardHookManager;
5 | private readonly MouseHookListener m_MouseHookManager;
6 |
7 | public TestFormHookListeners()
8 | {
9 | InitializeComponent();
10 | //m_KeyboardHookManager = new KeyboardHookListener(new GlobalHooker());
11 | //m_KeyboardHookManager.Enabled = true;
12 |
13 | m_MouseHookManager = new MouseHookListener( new GlobalHooker() ) { Enabled = true };
14 |
15 | HotKeySetCollection hkscoll = new HotKeySetCollection();
16 | m_KeyboardHookManager = new HotKeySetsListener( hkscoll, new GlobalHooker() ) { Enabled = true };
17 |
18 | BuildHotKeyTests( hkscoll );
19 | }
20 |
21 | private void BuildHotKeyTests( HotKeySetCollection hkscoll )
22 | {
23 | //Hot Keys are enabled by default. Use the Enabled property to adjust.
24 | hkscoll.Add( BindHotKeySet( new[] { Keys.T, Keys.LShiftKey }, null, OnHotKeyDownOnce1, OnHotKeyDownHold1, OnHotKeyUp1, "test1" ) );
25 | hkscoll.Add( BindHotKeySet( new[] { Keys.T, Keys.LControlKey, Keys.RControlKey }, new[] { Keys.LControlKey, Keys.RControlKey }, OnHotKeyDownGeneral2, OnHotKeyDownGeneral2, OnHotKeyUp1, "test2" ) );
26 | }
27 |
28 | private static HotKeySet BindHotKeySet( IEnumerable ks,
29 | IEnumerable xorKeys,
30 | HotKeySet.HotKeyHandler onEventDownOnce,
31 | HotKeySet.HotKeyHandler onEventDownHold,
32 | HotKeySet.HotKeyHandler onEventUp,
33 | string name )
34 | {
35 |
36 | //Declare ALL Keys that will be available in this set, including any keys you want to register as an either/or subset
37 | HotKeySet hks = new HotKeySet( ks );
38 |
39 | //Indicates that the keys in this array will be treated as an OR rather than AND: LShiftKey or RShiftKey
40 | //The keys MUST be a subset of the ks Keys array.
41 | if ( hks.RegisterExclusiveOrKey( xorKeys ) == Keys.None ) //Keys.None indicates an error
42 | {
43 | MessageBox.Show( null, @"Unable to register subset: " + String.Join( ", ", xorKeys ),
44 | @"Subset registration error", MessageBoxButtons.OK, MessageBoxIcon.Error );
45 | }
46 |
47 | hks.OnHotKeysDownOnce += onEventDownOnce; //The first time the key is down
48 | hks.OnHotKeysDownHold += onEventDownHold; //Fired as long as the user holds the hot keys down but is not fired the first time.
49 | hks.OnHotKeysUp += onEventUp; //Whenever a key from the set is no longer being held down
50 |
51 | hks.Name = ( name ?? String.Empty );
52 |
53 | return hks;
54 |
55 | }
56 |
57 | private void GeneralHotKeyEvent( object sender, DateTime timeTriggered, string eventType )
58 | {
59 | HotKeySet hks = sender as HotKeySet;
60 | string kstring = String.Join( ", ", hks.HotKeys );
61 | Log( String.Format( "{0}: {2} {1} - {3}\r\n", timeTriggered.TimeOfDay, eventType, hks.Name, kstring ) );
62 | }
63 |
64 | private void OnHotKeyDownGeneral2( object sender, HotKeyArgs e )
65 | {
66 | GeneralHotKeyEvent( sender, e.Time, "ONCE/HOLD" );
67 | }
68 |
69 | private void OnHotKeyDownOnce1( object sender, HotKeyArgs e )
70 | {
71 | GeneralHotKeyEvent( sender, e.Time, "ONCE" );
72 | }
73 |
74 | private void OnHotKeyDownHold1( object sender, HotKeyArgs e )
75 | {
76 | GeneralHotKeyEvent( sender, e.Time, "HOLD" );
77 | }
78 |
79 | private void OnHotKeyUp1( object sender, HotKeyArgs e )
80 | {
81 | GeneralHotKeyEvent( sender, e.Time, "UP" );
82 | }
83 |
84 |
85 |
86 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/IMouseEvents.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Windows.Forms;
7 |
8 | namespace Gma.System.MouseKeyHook
9 | {
10 | ///
11 | /// Provides all mouse events.
12 | ///
13 | public interface IMouseEvents
14 | {
15 | ///
16 | /// Occurs when the mouse pointer is moved.
17 | ///
18 | event MouseEventHandler MouseMove;
19 |
20 | ///
21 | /// Occurs when the mouse pointer is moved.
22 | ///
23 | ///
24 | /// This event provides extended arguments of type enabling you to
25 | /// suppress further processing of mouse movement in other applications.
26 | ///
27 | event EventHandler MouseMoveExt;
28 |
29 | ///
30 | /// Occurs when a click was performed by the mouse.
31 | ///
32 | event MouseEventHandler MouseClick;
33 |
34 | ///
35 | /// Occurs when the mouse a mouse button is pressed.
36 | ///
37 | event MouseEventHandler MouseDown;
38 |
39 | ///
40 | /// Occurs when the mouse a mouse button is pressed.
41 | ///
42 | ///
43 | /// This event provides extended arguments of type enabling you to
44 | /// suppress further processing of mouse click in other applications.
45 | ///
46 | event EventHandler MouseDownExt;
47 |
48 | ///
49 | /// Occurs when a mouse button is released.
50 | ///
51 | event MouseEventHandler MouseUp;
52 |
53 | ///
54 | /// Occurs when a mouse button is released.
55 | ///
56 | ///
57 | /// This event provides extended arguments of type enabling you to
58 | /// suppress further processing of mouse click in other applications.
59 | ///
60 | event EventHandler MouseUpExt;
61 |
62 |
63 | ///
64 | /// Occurs when the mouse wheel moves.
65 | ///
66 | event MouseEventHandler MouseWheel;
67 |
68 | ///
69 | /// Occurs when the mouse wheel moves.
70 | ///
71 | ///
72 | /// This event provides extended arguments of type enabling you to
73 | /// suppress further processing of mouse wheel moves in other applications.
74 | ///
75 | event EventHandler MouseWheelExt;
76 |
77 | ///
78 | /// Occurs when a mouse button is double-clicked.
79 | ///
80 | event MouseEventHandler MouseDoubleClick;
81 |
82 | ///
83 | /// Occurs when a drag event has started (left button held down whilst moving more than the system drag threshold).
84 | ///
85 | event MouseEventHandler MouseDragStarted;
86 |
87 | ///
88 | /// Occurs when a drag event has started (left button held down whilst moving more than the system drag threshold).
89 | ///
90 | ///
91 | /// This event provides extended arguments of type enabling you to
92 | /// suppress further processing of mouse movement in other applications.
93 | ///
94 | event EventHandler MouseDragStartedExt;
95 |
96 | ///
97 | /// Occurs when a drag event has completed.
98 | ///
99 | event MouseEventHandler MouseDragFinished;
100 |
101 | ///
102 | /// Occurs when a drag event has completed.
103 | ///
104 | ///
105 | /// This event provides extended arguments of type enabling you to
106 | /// suppress further processing of mouse movement in other applications.
107 | ///
108 | event EventHandler MouseDragFinishedExt;
109 | }
110 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/KeyPressEventArgsExt.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Runtime.InteropServices;
8 | using System.Windows.Forms;
9 | using Gma.System.MouseKeyHook.Implementation;
10 | using Gma.System.MouseKeyHook.WinApi;
11 |
12 | namespace Gma.System.MouseKeyHook
13 | {
14 | ///
15 | /// Provides extended data for the event.
16 | ///
17 | public class KeyPressEventArgsExt : KeyPressEventArgs
18 | {
19 | internal KeyPressEventArgsExt(char keyChar, int timestamp)
20 | : base(keyChar)
21 | {
22 | IsNonChar = keyChar == (char) 0x0;
23 | Timestamp = timestamp;
24 | }
25 |
26 | ///
27 | /// Initializes a new instance of the class.
28 | ///
29 | ///
30 | /// Character corresponding to the key pressed. 0 char if represents a system or functional non char
31 | /// key.
32 | ///
33 | public KeyPressEventArgsExt(char keyChar)
34 | : this(keyChar, Environment.TickCount)
35 | {
36 | }
37 |
38 | ///
39 | /// True if represents a system or functional non char key.
40 | ///
41 | public bool IsNonChar { get; }
42 |
43 | ///
44 | /// The system tick count of when the event occurred.
45 | ///
46 | public int Timestamp { get; }
47 |
48 | internal static IEnumerable FromRawDataApp(CallbackData data)
49 | {
50 | var wParam = data.WParam;
51 | var lParam = data.LParam;
52 |
53 | //http://msdn.microsoft.com/en-us/library/ms644984(v=VS.85).aspx
54 |
55 | const uint maskKeydown = 0x40000000; // for bit 30
56 | const uint maskKeyup = 0x80000000; // for bit 31
57 | const uint maskScanCode = 0xff0000; // for bit 23-16
58 |
59 | var flags = (uint) lParam.ToInt64();
60 |
61 | //bit 30 Specifies the previous key state. The value is 1 if the key is down before the message is sent; it is 0 if the key is up.
62 | var wasKeyDown = (flags & maskKeydown) > 0;
63 | //bit 31 Specifies the transition state. The value is 0 if the key is being pressed and 1 if it is being released.
64 | var isKeyReleased = (flags & maskKeyup) > 0;
65 |
66 | if (!wasKeyDown && !isKeyReleased)
67 | yield break;
68 |
69 | var virtualKeyCode = (int) wParam;
70 | var scanCode = checked((int) (flags & maskScanCode));
71 | const int fuState = 0;
72 |
73 | char[] chars;
74 |
75 | KeyboardNativeMethods.TryGetCharFromKeyboardState(virtualKeyCode, scanCode, fuState, out chars);
76 | if (chars == null) yield break;
77 | foreach (var ch in chars)
78 | yield return new KeyPressEventArgsExt(ch);
79 | }
80 |
81 | internal static IEnumerable FromRawDataGlobal(CallbackData data)
82 | {
83 | var wParam = data.WParam;
84 | var lParam = data.LParam;
85 |
86 | if ((int) wParam != Messages.WM_KEYDOWN && (int) wParam != Messages.WM_SYSKEYDOWN)
87 | yield break;
88 |
89 | var keyboardHookStruct =
90 | (KeyboardHookStruct) Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
91 |
92 | var virtualKeyCode = keyboardHookStruct.VirtualKeyCode;
93 | var scanCode = keyboardHookStruct.ScanCode;
94 | var fuState = keyboardHookStruct.Flags;
95 |
96 | if (virtualKeyCode == KeyboardNativeMethods.VK_PACKET)
97 | {
98 | var ch = (char) scanCode;
99 | yield return new KeyPressEventArgsExt(ch, keyboardHookStruct.Time);
100 | }
101 | else
102 | {
103 | char[] chars;
104 | KeyboardNativeMethods.TryGetCharFromKeyboardState(virtualKeyCode, scanCode, fuState, out chars);
105 | if (chars == null) yield break;
106 | foreach (var current in chars)
107 | yield return new KeyPressEventArgsExt(current, keyboardHookStruct.Time);
108 | }
109 | }
110 | }
111 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/KeyboardState.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Windows.Forms;
9 | using Gma.System.MouseKeyHook.WinApi;
10 |
11 | namespace Gma.System.MouseKeyHook.Implementation
12 | {
13 | ///
14 | /// Contains a snapshot of a keyboard state at certain moment and provides methods
15 | /// of querying whether specific keys are pressed or locked.
16 | ///
17 | ///
18 | /// This class is basically a managed wrapper of GetKeyboardState API function
19 | /// http://msdn.microsoft.com/en-us/library/ms646299
20 | ///
21 | public class KeyboardState
22 | {
23 | private readonly byte[] m_KeyboardStateNative;
24 |
25 | private KeyboardState(byte[] keyboardStateNative)
26 | {
27 | m_KeyboardStateNative = keyboardStateNative;
28 | }
29 |
30 | ///
31 | /// Makes a snapshot of a keyboard state to the moment of call and returns an
32 | /// instance of class.
33 | ///
34 | /// An instance of class representing a snapshot of keyboard state at certain moment.
35 | public static KeyboardState GetCurrent()
36 | {
37 | var keyboardStateNative = new byte[256];
38 | KeyboardNativeMethods.GetKeyboardState(keyboardStateNative);
39 | return new KeyboardState(keyboardStateNative);
40 | }
41 |
42 | internal byte[] GetNativeState()
43 | {
44 | return m_KeyboardStateNative;
45 | }
46 |
47 | ///
48 | /// Indicates whether specified key was down at the moment when snapshot was created or not.
49 | ///
50 | /// Key (corresponds to the virtual code of the key)
51 | /// true if key was down, false - if key was up.
52 | public bool IsDown(Keys key)
53 | {
54 | if ((int)key < 256) return IsDownRaw(key);
55 | if (key == Keys.Alt) return IsDownRaw(Keys.LMenu) || IsDownRaw(Keys.RMenu);
56 | if (key == Keys.Shift) return IsDownRaw(Keys.LShiftKey) || IsDownRaw(Keys.RShiftKey);
57 | if (key == Keys.Control) return IsDownRaw(Keys.LControlKey) || IsDownRaw(Keys.RControlKey);
58 | return false;
59 | }
60 |
61 | private bool IsDownRaw(Keys key)
62 | {
63 | var keyState = GetKeyState(key);
64 | var isDown = GetHighBit(keyState);
65 | return isDown;
66 | }
67 |
68 | ///
69 | /// Indicate weather specified key was toggled at the moment when snapshot was created or not.
70 | ///
71 | /// Key (corresponds to the virtual code of the key)
72 | ///
73 | /// true if toggle key like (CapsLock, NumLocke, etc.) was on. false if it was off.
74 | /// Ordinal (non toggle) keys return always false.
75 | ///
76 | public bool IsToggled(Keys key)
77 | {
78 | var keyState = GetKeyState(key);
79 | var isToggled = GetLowBit(keyState);
80 | return isToggled;
81 | }
82 |
83 | ///
84 | /// Indicates weather every of specified keys were down at the moment when snapshot was created.
85 | /// The method returns false if even one of them was up.
86 | ///
87 | /// Keys to verify whether they were down or not.
88 | /// true - all were down. false - at least one was up.
89 | public bool AreAllDown(IEnumerable keys)
90 | {
91 | return keys.All(IsDown);
92 | }
93 |
94 | private byte GetKeyState(Keys key)
95 | {
96 | var virtualKeyCode = (int) key;
97 | if (virtualKeyCode < 0 || virtualKeyCode > 255)
98 | throw new ArgumentOutOfRangeException("key", key, "The value must be between 0 and 255.");
99 | return m_KeyboardStateNative[virtualKeyCode];
100 | }
101 |
102 | private static bool GetHighBit(byte value)
103 | {
104 | return value >> 7 != 0;
105 | }
106 |
107 | private static bool GetLowBit(byte value)
108 | {
109 | return (value & 1) != 0;
110 | }
111 | }
112 | }
--------------------------------------------------------------------------------
/Autofarmer/Autofarm.Multibox.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows.Forms;
7 | using System.Diagnostics;
8 | using System.Runtime.InteropServices;
9 | using Gma.System.MouseKeyHook;
10 |
11 | namespace Autofarmer {
12 | public partial class Autofarm {
13 |
14 | [DllImport("user32.dll")]
15 | [return: MarshalAs(UnmanagedType.Bool)]
16 | static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
17 |
18 | [DllImport("user32.dll")]
19 | private static extern IntPtr GetForegroundWindow();
20 |
21 | [DllImport("user32.dll")]
22 | private static extern Int32 GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
23 |
24 | [StructLayout(LayoutKind.Sequential)]
25 | private struct RECT {
26 | public int Left;
27 | public int Top;
28 | public int Right;
29 | public int Bottom;
30 | }
31 |
32 | IKeyboardMouseEvents kmEvents = Hook.GlobalEvents(); // GlobalEvents() or AppEvents() ?
33 |
34 | private void HookListener() {
35 | Console.WriteLine("HOOKING");
36 | kmEvents.KeyDown += HookKeyDown;
37 | kmEvents.KeyUp += HookKeyUp;
38 | kmEvents.MouseDownExt += HookMouseDown;
39 | kmEvents.MouseUpExt += HookMouseUp;
40 | }
41 |
42 | private void UnhookListener() {
43 | Console.WriteLine("UNHOOKING");
44 | if (kmEvents == null) return;
45 | kmEvents.KeyDown -= HookKeyDown;
46 | kmEvents.KeyUp -= HookKeyUp;
47 | kmEvents.MouseDownExt -= HookMouseDown;
48 | kmEvents.MouseUpExt -= HookMouseUp;
49 |
50 | kmEvents.Dispose();
51 | }
52 |
53 | private void HookKeyDown(object sender, KeyEventArgs e) {
54 | e.Handled = true;
55 | IntPtr hWnd;
56 | IntPtr active = GetForegroundWindow();
57 |
58 | // The way I'm doing it right now is kind of awful
59 | // It's low-level, even though I don't need it to be
60 | // And it's global, even though I don't need it to be
61 | if (GetHandleProcessName(active) == "Growtopia") {
62 | foreach (Process process in processes) {
63 | Console.WriteLine("KeyDown: \t{0}", e.KeyCode);
64 | hWnd = process.MainWindowHandle;
65 | // WM_KEYDOWN = 0x100
66 | PostMessage(hWnd, 0x100, (IntPtr)e.KeyCode, IntPtr.Zero);
67 | }
68 | }
69 |
70 | }
71 |
72 | private void HookKeyUp(object sender, KeyEventArgs e) {
73 | e.Handled = true;
74 | IntPtr hWnd;
75 | IntPtr active = GetForegroundWindow();
76 |
77 | if (GetHandleProcessName(active) == "Growtopia") {
78 | foreach (Process process in processes) {
79 | Console.WriteLine("KeyUp: \t{0}", e.KeyCode);
80 | hWnd = process.MainWindowHandle;
81 | // WM_KEYUP = 0x101
82 | PostMessage(hWnd, 0x101, (IntPtr)e.KeyCode, IntPtr.Zero);
83 | }
84 | }
85 | }
86 |
87 | private void HookMouseDown(object sender, MouseEventExtArgs e) {
88 | IntPtr hWnd;
89 | IntPtr active = GetForegroundWindow();
90 |
91 | if (GetHandleProcessName(active) == "Growtopia") {
92 | e.Handled = true; // Prevent further processing of the event in other applications
93 | int relativeX;
94 | int relativeY;
95 |
96 | foreach (Process process in processes) {
97 | hWnd = process.MainWindowHandle;
98 |
99 | RECT relativeBox = new RECT();
100 | GetWindowRect(active, ref relativeBox);
101 |
102 | relativeX = e.Point.X - relativeBox.Left;
103 | relativeY = e.Point.Y - relativeBox.Top;
104 |
105 | //Console.WriteLine("X: " + e.Point.X + " Y: " + e.Point.Y);
106 | PostMessage(hWnd, 0x201, new IntPtr(0x1), (IntPtr)((relativeY << 16) | (relativeX & 0xffff)));
107 | }
108 | }
109 | }
110 |
111 | private void HookMouseUp(object sender, MouseEventExtArgs e) {
112 | IntPtr hWnd;
113 | IntPtr active = GetForegroundWindow();
114 | if (GetHandleProcessName(active) == "Growtopia") {
115 | e.Handled = true;
116 | int relativeX;
117 | int relativeY;
118 |
119 | foreach (Process process in processes) {
120 | hWnd = process.MainWindowHandle;
121 |
122 | RECT relativeBox = new RECT();
123 | GetWindowRect(active, ref relativeBox);
124 |
125 | relativeX = e.Point.X - relativeBox.Left;
126 | relativeY = e.Point.Y - relativeBox.Top;
127 |
128 | PostMessage(hWnd, 0x202, new IntPtr(0x1), (IntPtr)((relativeY << 16) | (relativeX & 0xffff)));
129 | }
130 | }
131 | }
132 |
133 | private string GetHandleProcessName(IntPtr hWnd) {
134 | //IntPtr hWnd = GetForegroundWindow();
135 |
136 | if (hWnd == null)
137 | return "Unknown";
138 |
139 | uint pid;
140 | GetWindowThreadProcessId(hWnd, out pid);
141 |
142 | foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcesses()) {
143 | if (p.Id == pid)
144 | return p.ProcessName;
145 | }
146 |
147 | return "Unknown";
148 | }
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/KeyCombinationExtensions.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2010-2018 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using Gma.System.MouseKeyHook.Implementation;
9 |
10 | namespace Gma.System.MouseKeyHook
11 | {
12 | ///
13 | /// Extension methods to detect key combinations
14 | ///
15 | public static class KeyCombinationExtensions
16 | {
17 | ///
18 | /// Detects a key or key combination and triggers the corresponding action.
19 | ///
20 | ///
21 | /// An instance of Global or Application hook. Use or to
22 | /// create it.
23 | ///
24 | ///
25 | /// This map contains the list of key combinations mapped to corresponding actions. You can use a dictionary initilizer
26 | /// to easily create it.
27 | /// Whenever a listed combination will be detected a corresponding action will be triggered.
28 | ///
29 | ///
30 | /// This optional action will be executed when some key was pressed but it was not part of any wanted combinations.
31 | ///
32 | public static void OnCombination(this IKeyboardEvents source,
33 | IEnumerable> map, Action reset = null)
34 | {
35 | var watchlists = map.GroupBy(k => k.Key.TriggerKey)
36 | .ToDictionary(g => g.Key, g => g.ToArray());
37 | source.KeyDown += (sender, e) =>
38 | {
39 | KeyValuePair[] element;
40 | var found = watchlists.TryGetValue(e.KeyCode, out element);
41 | if (!found)
42 | {
43 | reset?.Invoke();
44 | return;
45 | }
46 | var state = KeyboardState.GetCurrent();
47 | var action = reset;
48 | var maxLength = 0;
49 | foreach (var current in element)
50 | {
51 | var matches = current.Key.Chord.All(state.IsDown);
52 | if (!matches) continue;
53 | if (maxLength > current.Key.ChordLength) continue;
54 | maxLength = current.Key.ChordLength;
55 | action = current.Value;
56 | }
57 | action?.Invoke();
58 | };
59 | }
60 |
61 |
62 | ///
63 | /// Detects a key or key combination sequence and triggers the corresponding action.
64 | ///
65 | ///
66 | /// An instance of Global or Application hook. Use or
67 | /// to create it.
68 | ///
69 | ///
70 | /// This map contains the list of sequences mapped to corresponding actions. You can use a dictionary initilizer to
71 | /// easily create it.
72 | /// Whenever a listed sequnce will be detected a corresponding action will be triggered. If two or more sequences match
73 | /// the longest one will be used.
74 | /// Example: sequences may A,B,C and B,C might be detected simultanously if user pressed first A then B then C. In this
75 | /// case only action corresponding
76 | /// to 'A,B,C' will be triggered.
77 | ///
78 | public static void OnSequence(this IKeyboardEvents source, IEnumerable> map)
79 | {
80 | var actBySeq = map.ToArray();
81 | var endsWith = new Func, Sequence, bool>((chords, sequence) =>
82 | {
83 | var skipCount = chords.Count - sequence.Length;
84 | return skipCount >= 0 && chords.Skip(skipCount).SequenceEqual(sequence);
85 | });
86 |
87 | var max = actBySeq.Select(p => p.Key).Max(c => c.Length);
88 | var min = actBySeq.Select(p => p.Key).Min(c => c.Length);
89 | var buffer = new Queue(max);
90 |
91 | var wrapMap = actBySeq.SelectMany(p => p.Key).Select(c => new KeyValuePair(c, () =>
92 | {
93 | buffer.Enqueue(c);
94 | if (buffer.Count > max) buffer.Dequeue();
95 | if (buffer.Count < min) return;
96 | //Invoke action corresponding to the longest matching sequence
97 | actBySeq
98 | .Where(pair => endsWith(buffer, pair.Key))
99 | .OrderBy(pair => pair.Key.Length)
100 | .Select(pair => pair.Value)
101 | .LastOrDefault()
102 | ?.Invoke();
103 | }));
104 |
105 | OnCombination(source, wrapMap, buffer.Clear);
106 | }
107 | }
108 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/EventFacade.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Windows.Forms;
7 |
8 | namespace Gma.System.MouseKeyHook.Implementation
9 | {
10 | internal abstract class EventFacade : IKeyboardMouseEvents
11 | {
12 | private KeyListener m_KeyListenerCache;
13 | private MouseListener m_MouseListenerCache;
14 |
15 | public event KeyEventHandler KeyDown
16 | {
17 | add { GetKeyListener().KeyDown += value; }
18 | remove { GetKeyListener().KeyDown -= value; }
19 | }
20 |
21 | public event KeyPressEventHandler KeyPress
22 | {
23 | add { GetKeyListener().KeyPress += value; }
24 | remove { GetKeyListener().KeyPress -= value; }
25 | }
26 |
27 | public event KeyEventHandler KeyUp
28 | {
29 | add { GetKeyListener().KeyUp += value; }
30 | remove { GetKeyListener().KeyUp -= value; }
31 | }
32 |
33 | public event MouseEventHandler MouseMove
34 | {
35 | add { GetMouseListener().MouseMove += value; }
36 | remove { GetMouseListener().MouseMove -= value; }
37 | }
38 |
39 | public event EventHandler MouseMoveExt
40 | {
41 | add { GetMouseListener().MouseMoveExt += value; }
42 | remove { GetMouseListener().MouseMoveExt -= value; }
43 | }
44 |
45 | public event MouseEventHandler MouseClick
46 | {
47 | add { GetMouseListener().MouseClick += value; }
48 | remove { GetMouseListener().MouseClick -= value; }
49 | }
50 |
51 | public event MouseEventHandler MouseDown
52 | {
53 | add { GetMouseListener().MouseDown += value; }
54 | remove { GetMouseListener().MouseDown -= value; }
55 | }
56 |
57 | public event EventHandler MouseDownExt
58 | {
59 | add { GetMouseListener().MouseDownExt += value; }
60 | remove { GetMouseListener().MouseDownExt -= value; }
61 | }
62 |
63 | public event MouseEventHandler MouseUp
64 | {
65 | add { GetMouseListener().MouseUp += value; }
66 | remove { GetMouseListener().MouseUp -= value; }
67 | }
68 |
69 | public event EventHandler MouseUpExt
70 | {
71 | add { GetMouseListener().MouseUpExt += value; }
72 | remove { GetMouseListener().MouseUpExt -= value; }
73 | }
74 |
75 | public event MouseEventHandler MouseWheel
76 | {
77 | add { GetMouseListener().MouseWheel += value; }
78 | remove { GetMouseListener().MouseWheel -= value; }
79 | }
80 |
81 | public event EventHandler MouseWheelExt
82 | {
83 | add { GetMouseListener().MouseWheelExt += value; }
84 | remove { GetMouseListener().MouseWheelExt -= value; }
85 | }
86 |
87 | public event MouseEventHandler MouseDoubleClick
88 | {
89 | add { GetMouseListener().MouseDoubleClick += value; }
90 | remove { GetMouseListener().MouseDoubleClick -= value; }
91 | }
92 |
93 | public event MouseEventHandler MouseDragStarted
94 | {
95 | add { GetMouseListener().MouseDragStarted += value; }
96 | remove { GetMouseListener().MouseDragStarted -= value; }
97 | }
98 |
99 | public event EventHandler MouseDragStartedExt
100 | {
101 | add { GetMouseListener().MouseDragStartedExt += value; }
102 | remove { GetMouseListener().MouseDragStartedExt -= value; }
103 | }
104 |
105 | public event MouseEventHandler MouseDragFinished
106 | {
107 | add { GetMouseListener().MouseDragFinished += value; }
108 | remove { GetMouseListener().MouseDragFinished -= value; }
109 | }
110 |
111 | public event EventHandler MouseDragFinishedExt
112 | {
113 | add { GetMouseListener().MouseDragFinishedExt += value; }
114 | remove { GetMouseListener().MouseDragFinishedExt -= value; }
115 | }
116 |
117 | public void Dispose()
118 | {
119 | if (m_MouseListenerCache != null) m_MouseListenerCache.Dispose();
120 | if (m_KeyListenerCache != null) m_KeyListenerCache.Dispose();
121 | }
122 |
123 | private KeyListener GetKeyListener()
124 | {
125 | var target = m_KeyListenerCache;
126 | if (target != null) return target;
127 | target = CreateKeyListener();
128 | m_KeyListenerCache = target;
129 | return target;
130 | }
131 |
132 | private MouseListener GetMouseListener()
133 | {
134 | var target = m_MouseListenerCache;
135 | if (target != null) return target;
136 | target = CreateMouseListener();
137 | m_MouseListenerCache = target;
138 | return target;
139 | }
140 |
141 | protected abstract MouseListener CreateMouseListener();
142 | protected abstract KeyListener CreateKeyListener();
143 | }
144 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/HookNativeMethods.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 |
8 | namespace Gma.System.MouseKeyHook.WinApi
9 | {
10 | internal static class HookNativeMethods
11 | {
12 | ///
13 | /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
14 | /// A hook procedure can call this function either before or after processing the hook information.
15 | ///
16 | /// This parameter is ignored.
17 | /// [in] Specifies the hook code passed to the current hook procedure.
18 | /// [in] Specifies the wParam value passed to the current hook procedure.
19 | /// [in] Specifies the lParam value passed to the current hook procedure.
20 | /// This value is returned by the next hook procedure in the chain.
21 | ///
22 | /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
23 | ///
24 | [DllImport("user32.dll", CharSet = CharSet.Auto,
25 | CallingConvention = CallingConvention.StdCall)]
26 | internal static extern IntPtr CallNextHookEx(
27 | IntPtr idHook,
28 | int nCode,
29 | IntPtr wParam,
30 | IntPtr lParam);
31 |
32 | ///
33 | /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
34 | /// You would install a hook procedure to monitor the system for certain types of events. These events
35 | /// are associated either with a specific thread or with all threads in the same desktop as the calling thread.
36 | ///
37 | ///
38 | /// [in] Specifies the type of hook procedure to be installed. This parameter can be one of the following values.
39 | ///
40 | ///
41 | /// [in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a
42 | /// thread created by a different process, the lpfn parameter must point to a hook procedure in a dynamic-link
43 | /// library (DLL). Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
44 | ///
45 | ///
46 | /// [in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
47 | /// The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
48 | /// the current process and if the hook procedure is within the code associated with the current process.
49 | ///
50 | ///
51 | /// [in] Specifies the identifier of the thread with which the hook procedure is to be associated.
52 | /// If this parameter is zero, the hook procedure is associated with all existing threads running in the
53 | /// same desktop as the calling thread.
54 | ///
55 | ///
56 | /// If the function succeeds, the return value is the handle to the hook procedure.
57 | /// If the function fails, the return value is NULL. To get extended error information, call GetLastError.
58 | ///
59 | ///
60 | /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
61 | ///
62 | [DllImport("user32.dll", CharSet = CharSet.Auto,
63 | CallingConvention = CallingConvention.StdCall, SetLastError = true)]
64 | internal static extern HookProcedureHandle SetWindowsHookEx(
65 | int idHook,
66 | HookProcedure lpfn,
67 | IntPtr hMod,
68 | int dwThreadId);
69 |
70 | ///
71 | /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx
72 | /// function.
73 | ///
74 | ///
75 | /// [in] Handle to the hook to be removed. This parameter is a hook handle obtained by a previous call to
76 | /// SetWindowsHookEx.
77 | ///
78 | ///
79 | /// If the function succeeds, the return value is nonzero.
80 | /// If the function fails, the return value is zero. To get extended error information, call GetLastError.
81 | ///
82 | ///
83 | /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
84 | ///
85 | [DllImport("user32.dll", CharSet = CharSet.Auto,
86 | CallingConvention = CallingConvention.StdCall, SetLastError = true)]
87 | internal static extern int UnhookWindowsHookEx(IntPtr idHook);
88 | }
89 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Combination.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2010-2018 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Linq;
8 | using System.Windows.Forms;
9 | using Gma.System.MouseKeyHook.Implementation;
10 |
11 | namespace Gma.System.MouseKeyHook
12 | {
13 | ///
14 | /// Used to represent a key combination as frequently used in application as shortcuts.
15 | /// e.g. Alt+Shift+R. This combination is triggered when 'R' is pressed after 'Alt' and 'Shift' are already down.
16 | ///
17 | public class Combination
18 | {
19 | private readonly Chord _chord;
20 |
21 | private Combination(Keys triggerKey, IEnumerable chordKeys)
22 | : this(triggerKey, new Chord(chordKeys))
23 | {
24 | }
25 |
26 | private Combination(Keys triggerKey, Chord chord)
27 | {
28 | TriggerKey = triggerKey.Normalize();
29 | _chord = chord;
30 | }
31 |
32 | ///
33 | /// Last key which triggers the combination.
34 | ///
35 | public Keys TriggerKey { get; }
36 |
37 | ///
38 | /// Keys which all must be alredy down when trigger key is pressed.
39 | ///
40 | public IEnumerable Chord
41 | {
42 | get { return _chord; }
43 | }
44 |
45 | ///
46 | /// Number of chord (modifier) keys which must be already down when the trigger key is pressed.
47 | ///
48 | public int ChordLength
49 | {
50 | get { return _chord.Count; }
51 | }
52 |
53 | ///
54 | /// A chainable builder method to simplify chord creation. Used along with ,
55 | /// , , , .
56 | ///
57 | ///
58 | public static Combination TriggeredBy(Keys key)
59 | {
60 | return new Combination(key, (IEnumerable) new Chord(Enumerable.Empty()));
61 | }
62 |
63 | ///
64 | /// A chainable builder method to simplify chord creation. Used along with ,
65 | /// , , , .
66 | ///
67 | ///
68 | public Combination With(Keys key)
69 | {
70 | return new Combination(TriggerKey, Chord.Concat(Enumerable.Repeat(key, 1)));
71 | }
72 |
73 | ///
74 | /// A chainable builder method to simplify chord creation. Used along with ,
75 | /// , , , .
76 | ///
77 | public Combination Control()
78 | {
79 | return With(Keys.Control);
80 | }
81 |
82 | ///
83 | /// A chainable builder method to simplify chord creation. Used along with ,
84 | /// , , , .
85 | ///
86 | public Combination Alt()
87 | {
88 | return With(Keys.Alt);
89 | }
90 |
91 | ///
92 | /// A chainable builder method to simplify chord creation. Used along with ,
93 | /// , , , .
94 | ///
95 | public Combination Shift()
96 | {
97 | return With(Keys.Shift);
98 | }
99 |
100 |
101 | ///
102 | public override string ToString()
103 | {
104 | return string.Join("+", Chord.Concat(Enumerable.Repeat(TriggerKey, 1)));
105 | }
106 |
107 | ///
108 | /// TriggeredBy a chord from any string like this 'Alt+Shift+R'.
109 | /// Nothe that the trigger key must be the last one.
110 | ///
111 | public static Combination FromString(string trigger)
112 | {
113 | var parts = trigger
114 | .Split('+')
115 | .Select(p => Enum.Parse(typeof(Keys), p))
116 | .Cast();
117 | var stack = new Stack(parts);
118 | var triggerKey = stack.Pop();
119 | return new Combination(triggerKey, stack);
120 | }
121 |
122 | ///
123 | protected bool Equals(Combination other)
124 | {
125 | return
126 | TriggerKey == other.TriggerKey
127 | && Chord.Equals(other.Chord);
128 | }
129 |
130 | ///
131 | public override bool Equals(object obj)
132 | {
133 | if (ReferenceEquals(null, obj)) return false;
134 | if (ReferenceEquals(this, obj)) return true;
135 | if (obj.GetType() != GetType()) return false;
136 | return Equals((Combination) obj);
137 | }
138 |
139 | ///
140 | public override int GetHashCode()
141 | {
142 | return Chord.GetHashCode() ^
143 | (int) TriggerKey;
144 | }
145 | }
146 | }
--------------------------------------------------------------------------------
/Autofarmer/GlobalMouseHook.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Runtime.InteropServices;
5 | using System.Windows.Forms;
6 |
7 | namespace Utilities {
8 | class GlobalMouseHook {
9 | #region Constant, Structure and Delegate Definitions
10 | ///
11 | /// defines the callback type for the hook
12 | ///
13 | public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);
14 |
15 | public struct mouseHookStruct {
16 | public POINT pt;
17 | public uint mouseData;
18 | public uint flags;
19 | public uint time;
20 | public IntPtr dwExtraInfo;
21 | }
22 |
23 | public struct POINT {
24 | public int x;
25 | public int y;
26 | }
27 |
28 | const int WM_LBUTTONDOWN = 0x0201;
29 | const int WM_LBUTTONUP = 0x0202;
30 | const int WM_MOUSEMOVE = 0x0200;
31 | const int WM_MOUSEWHEEL = 0x020A;
32 | const int WM_RBUTTONDOWN = 0x0204;
33 | const int WM_RBUTTONUP = 0x0205;
34 | const int WM_LBUTTONDBLCLK = 0x0203;
35 | const int WM_MBUTTONDOWN = 0x0207;
36 | const int WM_MBUTTONUP = 0x0208;
37 | #endregion
38 |
39 | #region Instance Variables
40 | ///
41 | /// The collections of keys to watch for
42 | ///
43 | public List HookedKeys = new List();
44 | ///
45 | /// Handle to the hook, need this to unhook and call the next hook
46 | ///
47 | IntPtr hhook = IntPtr.Zero;
48 | private keyboardHookProc hookProcDelegate;
49 | #endregion
50 |
51 | #region Events
52 | ///
53 | /// Occurs when one of the hooked keys is pressed
54 | ///
55 | public event KeyEventHandler KeyDown;
56 | ///
57 | /// Occurs when one of the hooked keys is released
58 | ///
59 | public event KeyEventHandler KeyUp;
60 | #endregion
61 |
62 | #region Constructors and Destructors
63 | ///
64 | /// Initializes a new instance of the class and installs the keyboard hook.
65 | ///
66 | public GlobalMouseHook() {
67 | hookProcDelegate = hookProc;
68 | hook();
69 | }
70 |
71 | ///
72 | /// Releases unmanaged resources and performs other cleanup operations before the
73 | /// is reclaimed by garbage collection and uninstalls the keyboard hook.
74 | ///
75 | ~GlobalMouseHook() {
76 | unhook();
77 | }
78 | #endregion
79 |
80 | #region Public Methods
81 | ///
82 | /// Installs the global hook
83 | ///
84 | public void hook() {
85 | IntPtr hInstance = LoadLibrary("User32");
86 | hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProcDelegate, hInstance, 0);
87 | }
88 |
89 | ///
90 | /// Uninstalls the global hook
91 | ///
92 | public void unhook() {
93 | Console.WriteLine("Unhooking.");
94 | UnhookWindowsHookEx(hhook);
95 | }
96 |
97 | ///
98 | /// The callback for the keyboard hook
99 | ///
100 | /// The hook code, if it isn't >= 0, the function shouldn't do anyting
101 | /// The event type
102 | /// The keyhook event information
103 | ///
104 | public int hookProc(int code, int wParam, ref keyboardHookStruct lParam) {
105 | if (code >= 0) {
106 | Keys key = (Keys)lParam.vkCode;
107 | KeyEventArgs kea = new KeyEventArgs(key);
108 | if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null)) {
109 | KeyDown(this, kea);
110 | } else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null)) {
111 | KeyUp(this, kea);
112 | }
113 | if (kea.Handled)
114 | return 1;
115 | }
116 | return CallNextHookEx(hhook, code, wParam, ref lParam);
117 | }
118 | #endregion
119 |
120 | #region DLL imports
121 | ///
122 | /// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null
123 | ///
124 | /// The id of the event you want to hook
125 | /// The callback.
126 | /// The handle you want to attach the event to, can be null
127 | /// The thread you want to attach the event to, can be null
128 | /// a handle to the desired hook
129 | [DllImport("user32.dll")]
130 | static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
131 |
132 | ///
133 | /// Unhooks the windows hook.
134 | ///
135 | /// The hook handle that was returned from SetWindowsHookEx
136 | /// True if successful, false otherwise
137 | [DllImport("user32.dll")]
138 | static extern bool UnhookWindowsHookEx(IntPtr hInstance);
139 |
140 | ///
141 | /// Calls the next hook.
142 | ///
143 | /// The hook id
144 | /// The hook code
145 | /// The wparam.
146 | /// The lparam.
147 | ///
148 | [DllImport("user32.dll")]
149 | static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);
150 |
151 | ///
152 | /// Loads the library.
153 | ///
154 | /// Name of the library
155 | /// A handle to the library
156 | [DllImport("kernel32.dll")]
157 | static extern IntPtr LoadLibrary(string lpFileName);
158 | #endregion
159 | }
160 | }
161 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/WinApi/Messages.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | namespace Gma.System.MouseKeyHook.WinApi
6 | {
7 | internal static class Messages
8 | {
9 | //values from Winuser.h in Microsoft SDK.
10 |
11 | ///
12 | /// The WM_MOUSEMOVE message is posted to a window when the cursor moves.
13 | ///
14 | public const int WM_MOUSEMOVE = 0x200;
15 |
16 | ///
17 | /// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button
18 | ///
19 | public const int WM_LBUTTONDOWN = 0x201;
20 |
21 | ///
22 | /// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
23 | ///
24 | public const int WM_RBUTTONDOWN = 0x204;
25 |
26 | ///
27 | /// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button
28 | ///
29 | public const int WM_MBUTTONDOWN = 0x207;
30 |
31 | ///
32 | /// The WM_LBUTTONUP message is posted when the user releases the left mouse button
33 | ///
34 | public const int WM_LBUTTONUP = 0x202;
35 |
36 | ///
37 | /// The WM_RBUTTONUP message is posted when the user releases the right mouse button
38 | ///
39 | public const int WM_RBUTTONUP = 0x205;
40 |
41 | ///
42 | /// The WM_MBUTTONUP message is posted when the user releases the middle mouse button
43 | ///
44 | public const int WM_MBUTTONUP = 0x208;
45 |
46 | ///
47 | /// The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button
48 | ///
49 | public const int WM_LBUTTONDBLCLK = 0x203;
50 |
51 | ///
52 | /// The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button
53 | ///
54 | public const int WM_RBUTTONDBLCLK = 0x206;
55 |
56 | ///
57 | /// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
58 | ///
59 | public const int WM_MBUTTONDBLCLK = 0x209;
60 |
61 | ///
62 | /// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel.
63 | ///
64 | public const int WM_MOUSEWHEEL = 0x020A;
65 |
66 | ///
67 | /// The WM_XBUTTONDOWN message is posted when the user presses the first or second X mouse
68 | /// button.
69 | ///
70 | public const int WM_XBUTTONDOWN = 0x20B;
71 |
72 | ///
73 | /// The WM_XBUTTONUP message is posted when the user releases the first or second X mouse
74 | /// button.
75 | ///
76 | public const int WM_XBUTTONUP = 0x20C;
77 |
78 | ///
79 | /// The WM_XBUTTONDBLCLK message is posted when the user double-clicks the first or second
80 | /// X mouse button.
81 | ///
82 | /// Only windows that have the CS_DBLCLKS style can receive WM_XBUTTONDBLCLK messages.
83 | public const int WM_XBUTTONDBLCLK = 0x20D;
84 |
85 | ///
86 | /// The WM_MOUSEHWHEEL message Sent to the active window when the mouse's horizontal scroll
87 | /// wheel is tilted or rotated.
88 | ///
89 | public const int WM_MOUSEHWHEEL = 0x20E;
90 |
91 | ///
92 | /// The WM_KEYDOWN message is posted to the window with the keyboard focus when a non-system
93 | /// key is pressed. A non-system key is a key that is pressed when the ALT key is not pressed.
94 | ///
95 | public const int WM_KEYDOWN = 0x100;
96 |
97 | ///
98 | /// The WM_KEYUP message is posted to the window with the keyboard focus when a non-system
99 | /// key is released. A non-system key is a key that is pressed when the ALT key is not pressed,
100 | /// or a keyboard key that is pressed when a window has the keyboard focus.
101 | ///
102 | public const int WM_KEYUP = 0x101;
103 |
104 | ///
105 | /// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user
106 | /// presses the F10 key (which activates the menu bar) or holds down the ALT key and then
107 | /// presses another key. It also occurs when no window currently has the keyboard focus;
108 | /// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that
109 | /// receives the message can distinguish between these two contexts by checking the context
110 | /// code in the lParam parameter.
111 | ///
112 | public const int WM_SYSKEYDOWN = 0x104;
113 |
114 | ///
115 | /// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user
116 | /// releases a key that was pressed while the ALT key was held down. It also occurs when no
117 | /// window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent
118 | /// to the active window. The window that receives the message can distinguish between
119 | /// these two contexts by checking the context code in the lParam parameter.
120 | ///
121 | public const int WM_SYSKEYUP = 0x105;
122 | }
123 | }
--------------------------------------------------------------------------------
/Autofarmer/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/Autofarmer/MouseHook.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 | using System.Diagnostics;
4 |
5 | namespace GlobalLowLevelHooks {
6 | ///
7 | /// Class for intercepting low level Windows mouse hooks.
8 | ///
9 | public class MouseHook {
10 | ///
11 | /// Internal callback processing function
12 | ///
13 | private delegate IntPtr MouseHookHandler(int nCode, IntPtr wParam, IntPtr lParam);
14 | private MouseHookHandler hookHandler;
15 |
16 | ///
17 | /// Function to be called when defined even occurs
18 | ///
19 | /// MSLLHOOKSTRUCT mouse structure
20 | public delegate void MouseHookCallback(MSLLHOOKSTRUCT mouseStruct);
21 |
22 | #region Events
23 | public event MouseHookCallback LeftButtonDown;
24 | public event MouseHookCallback LeftButtonUp;
25 | public event MouseHookCallback RightButtonDown;
26 | public event MouseHookCallback RightButtonUp;
27 | public event MouseHookCallback MouseMove;
28 | public event MouseHookCallback MouseWheel;
29 | public event MouseHookCallback DoubleClick;
30 | public event MouseHookCallback MiddleButtonDown;
31 | public event MouseHookCallback MiddleButtonUp;
32 | #endregion
33 |
34 | ///
35 | /// Low level mouse hook's ID
36 | ///
37 | private IntPtr hookID = IntPtr.Zero;
38 |
39 | ///
40 | /// Install low level mouse hook
41 | ///
42 | /// Callback function
43 | public void Install() {
44 | hookHandler = HookFunc;
45 | hookID = SetHook(hookHandler);
46 | }
47 |
48 | ///
49 | /// Remove low level mouse hook
50 | ///
51 | public void Uninstall() {
52 | if (hookID == IntPtr.Zero)
53 | return;
54 |
55 | UnhookWindowsHookEx(hookID);
56 | hookID = IntPtr.Zero;
57 | }
58 |
59 | ///
60 | /// Destructor. Unhook current hook
61 | ///
62 | ~MouseHook() {
63 | Uninstall();
64 | }
65 |
66 | ///
67 | /// Sets hook and assigns its ID for tracking
68 | ///
69 | /// Internal callback function
70 | /// Hook ID
71 | private IntPtr SetHook(MouseHookHandler proc) {
72 | using (ProcessModule module = Process.GetCurrentProcess().MainModule)
73 | return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(module.ModuleName), 0);
74 | }
75 |
76 | ///
77 | /// Callback function
78 | ///
79 | private IntPtr HookFunc(int nCode, IntPtr wParam, IntPtr lParam) {
80 | // parse system messages
81 | if (nCode >= 0) {
82 | if (MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
83 | if (LeftButtonDown != null)
84 | LeftButtonDown((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
85 | if (MouseMessages.WM_LBUTTONUP == (MouseMessages)wParam)
86 | if (LeftButtonUp != null)
87 | LeftButtonUp((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
88 | if (MouseMessages.WM_RBUTTONDOWN == (MouseMessages)wParam)
89 | if (RightButtonDown != null)
90 | RightButtonDown((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
91 | if (MouseMessages.WM_RBUTTONUP == (MouseMessages)wParam)
92 | if (RightButtonUp != null)
93 | RightButtonUp((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
94 | if (MouseMessages.WM_MOUSEMOVE == (MouseMessages)wParam)
95 | if (MouseMove != null)
96 | MouseMove((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
97 | if (MouseMessages.WM_MOUSEWHEEL == (MouseMessages)wParam)
98 | if (MouseWheel != null)
99 | MouseWheel((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
100 | if (MouseMessages.WM_LBUTTONDBLCLK == (MouseMessages)wParam)
101 | if (DoubleClick != null)
102 | DoubleClick((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
103 | if (MouseMessages.WM_MBUTTONDOWN == (MouseMessages)wParam)
104 | if (MiddleButtonDown != null)
105 | MiddleButtonDown((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
106 | if (MouseMessages.WM_MBUTTONUP == (MouseMessages)wParam)
107 | if (MiddleButtonUp != null)
108 | MiddleButtonUp((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
109 | }
110 | return CallNextHookEx(hookID, nCode, wParam, lParam);
111 | }
112 |
113 | #region WinAPI
114 | private const int WH_MOUSE_LL = 14;
115 |
116 | private enum MouseMessages {
117 | WM_LBUTTONDOWN = 0x0201,
118 | WM_LBUTTONUP = 0x0202,
119 | WM_MOUSEMOVE = 0x0200,
120 | WM_MOUSEWHEEL = 0x020A,
121 | WM_RBUTTONDOWN = 0x0204,
122 | WM_RBUTTONUP = 0x0205,
123 | WM_LBUTTONDBLCLK = 0x0203,
124 | WM_MBUTTONDOWN = 0x0207,
125 | WM_MBUTTONUP = 0x0208
126 | }
127 |
128 | [StructLayout(LayoutKind.Sequential)]
129 | public struct POINT {
130 | public int x;
131 | public int y;
132 | }
133 |
134 | [StructLayout(LayoutKind.Sequential)]
135 | public struct MSLLHOOKSTRUCT {
136 | public POINT pt;
137 | public uint mouseData;
138 | public uint flags;
139 | public uint time;
140 | public IntPtr dwExtraInfo;
141 | }
142 |
143 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
144 | private static extern IntPtr SetWindowsHookEx(int idHook,
145 | MouseHookHandler lpfn, IntPtr hMod, uint dwThreadId);
146 |
147 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
148 | [return: MarshalAs(UnmanagedType.Bool)]
149 | public static extern bool UnhookWindowsHookEx(IntPtr hhk);
150 |
151 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
152 | private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
153 |
154 | [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
155 | private static extern IntPtr GetModuleHandle(string lpModuleName);
156 | #endregion
157 | }
158 | }
--------------------------------------------------------------------------------
/MouseHook.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 | using System.Diagnostics;
4 |
5 | // Based on MouseHook.cs : https://github.com/rvknth043/Global-Low-Level-Key-Board-And-Mouse-Hook/
6 |
7 | namespace GlobalLowLevelHooks {
8 | ///
9 | /// Class for intercepting low level Windows mouse hooks.
10 | ///
11 | public class MouseHook {
12 | ///
13 | /// Internal callback processing function
14 | ///
15 | private delegate IntPtr MouseHookHandler(int nCode, IntPtr wParam, IntPtr lParam);
16 | private MouseHookHandler hookHandler;
17 |
18 | ///
19 | /// Function to be called when defined even occurs
20 | ///
21 | /// MSLLHOOKSTRUCT mouse structure
22 | public delegate void MouseHookCallback(MSLLHOOKSTRUCT mouseStruct);
23 |
24 | #region Events
25 | public event MouseHookCallback LeftButtonDown;
26 | public event MouseHookCallback LeftButtonUp;
27 | public event MouseHookCallback RightButtonDown;
28 | public event MouseHookCallback RightButtonUp;
29 | public event MouseHookCallback MouseMove;
30 | public event MouseHookCallback MouseWheel;
31 | public event MouseHookCallback DoubleClick;
32 | public event MouseHookCallback MiddleButtonDown;
33 | public event MouseHookCallback MiddleButtonUp;
34 | #endregion
35 |
36 | ///
37 | /// Low level mouse hook's ID
38 | ///
39 | private IntPtr hookID = IntPtr.Zero;
40 |
41 | ///
42 | /// Install low level mouse hook
43 | ///
44 | /// Callback function
45 | public void Install() {
46 | hookHandler = HookFunc;
47 | hookID = SetHook(hookHandler);
48 | }
49 |
50 | ///
51 | /// Remove low level mouse hook
52 | ///
53 | public void Uninstall() {
54 | if (hookID == IntPtr.Zero)
55 | return;
56 |
57 | UnhookWindowsHookEx(hookID);
58 | hookID = IntPtr.Zero;
59 | }
60 |
61 | ///
62 | /// Destructor. Unhook current hook
63 | ///
64 | ~MouseHook() {
65 | Uninstall();
66 | }
67 |
68 | ///
69 | /// Sets hook and assigns its ID for tracking
70 | ///
71 | /// Internal callback function
72 | /// Hook ID
73 | private IntPtr SetHook(MouseHookHandler proc) {
74 | using (ProcessModule module = Process.GetCurrentProcess().MainModule)
75 | return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(module.ModuleName), 0);
76 | }
77 |
78 | ///
79 | /// Callback function
80 | ///
81 | private IntPtr HookFunc(int nCode, IntPtr wParam, IntPtr lParam) {
82 | // parse system messages
83 | if (nCode >= 0) {
84 | if (MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
85 | if (LeftButtonDown != null)
86 | LeftButtonDown((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
87 | if (MouseMessages.WM_LBUTTONUP == (MouseMessages)wParam)
88 | if (LeftButtonUp != null)
89 | LeftButtonUp((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
90 | if (MouseMessages.WM_RBUTTONDOWN == (MouseMessages)wParam)
91 | if (RightButtonDown != null)
92 | RightButtonDown((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
93 | if (MouseMessages.WM_RBUTTONUP == (MouseMessages)wParam)
94 | if (RightButtonUp != null)
95 | RightButtonUp((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
96 | if (MouseMessages.WM_MOUSEMOVE == (MouseMessages)wParam)
97 | if (MouseMove != null)
98 | MouseMove((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
99 | if (MouseMessages.WM_MOUSEWHEEL == (MouseMessages)wParam)
100 | if (MouseWheel != null)
101 | MouseWheel((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
102 | if (MouseMessages.WM_LBUTTONDBLCLK == (MouseMessages)wParam)
103 | if (DoubleClick != null)
104 | DoubleClick((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
105 | if (MouseMessages.WM_MBUTTONDOWN == (MouseMessages)wParam)
106 | if (MiddleButtonDown != null)
107 | MiddleButtonDown((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
108 | if (MouseMessages.WM_MBUTTONUP == (MouseMessages)wParam)
109 | if (MiddleButtonUp != null)
110 | MiddleButtonUp((MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)));
111 | }
112 | return 1;
113 | //return CallNextHookEx(hookID, nCode, wParam, lParam);
114 | }
115 |
116 | #region WinAPI
117 | private const int WH_MOUSE_LL = 14;
118 |
119 | private enum MouseMessages {
120 | WM_LBUTTONDOWN = 0x0201,
121 | WM_LBUTTONUP = 0x0202,
122 | WM_MOUSEMOVE = 0x0200,
123 | WM_MOUSEWHEEL = 0x020A,
124 | WM_RBUTTONDOWN = 0x0204,
125 | WM_RBUTTONUP = 0x0205,
126 | WM_LBUTTONDBLCLK = 0x0203,
127 | WM_MBUTTONDOWN = 0x0207,
128 | WM_MBUTTONUP = 0x0208
129 | }
130 |
131 | [StructLayout(LayoutKind.Sequential)]
132 | public struct POINT {
133 | public int x;
134 | public int y;
135 | }
136 |
137 | [StructLayout(LayoutKind.Sequential)]
138 | public struct MSLLHOOKSTRUCT {
139 | public POINT pt;
140 | public uint mouseData;
141 | public uint flags;
142 | public uint time;
143 | public IntPtr dwExtraInfo;
144 | }
145 |
146 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
147 | private static extern IntPtr SetWindowsHookEx(int idHook,
148 | MouseHookHandler lpfn, IntPtr hMod, uint dwThreadId);
149 |
150 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
151 | [return: MarshalAs(UnmanagedType.Bool)]
152 | public static extern bool UnhookWindowsHookEx(IntPtr hhk);
153 |
154 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
155 | private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
156 |
157 | [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
158 | private static extern IntPtr GetModuleHandle(string lpModuleName);
159 | #endregion
160 | }
161 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/KeyEventArgsExt.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 | using System.Windows.Forms;
8 | using Gma.System.MouseKeyHook.Implementation;
9 | using Gma.System.MouseKeyHook.WinApi;
10 |
11 | namespace Gma.System.MouseKeyHook
12 | {
13 | ///
14 | /// Provides extended argument data for the or
15 | /// event.
16 | ///
17 | public class KeyEventArgsExt : KeyEventArgs
18 | {
19 | ///
20 | /// Initializes a new instance of the class.
21 | ///
22 | ///
23 | public KeyEventArgsExt(Keys keyData)
24 | : base(keyData)
25 | {
26 | }
27 |
28 | internal KeyEventArgsExt(Keys keyData, int scanCode, int timestamp, bool isKeyDown, bool isKeyUp,
29 | bool isExtendedKey)
30 | : this(keyData)
31 | {
32 | ScanCode = scanCode;
33 | Timestamp = timestamp;
34 | IsKeyDown = isKeyDown;
35 | IsKeyUp = isKeyUp;
36 | IsExtendedKey = isExtendedKey;
37 | }
38 |
39 | ///
40 | /// The hardware scan code.
41 | ///
42 | public int ScanCode { get; }
43 |
44 | ///
45 | /// The system tick count of when the event occurred.
46 | ///
47 | public int Timestamp { get; }
48 |
49 | ///
50 | /// True if event signals key down..
51 | ///
52 | public bool IsKeyDown { get; }
53 |
54 | ///
55 | /// True if event signals key up.
56 | ///
57 | public bool IsKeyUp { get; }
58 |
59 | ///
60 | /// True if event signals, that the key is an extended key
61 | ///
62 | public bool IsExtendedKey { get; }
63 |
64 | internal static KeyEventArgsExt FromRawDataApp(CallbackData data)
65 | {
66 | var wParam = data.WParam;
67 | var lParam = data.LParam;
68 |
69 | //http://msdn.microsoft.com/en-us/library/ms644984(v=VS.85).aspx
70 |
71 | const uint maskKeydown = 0x40000000; // for bit 30
72 | const uint maskKeyup = 0x80000000; // for bit 31
73 | const uint maskExtendedKey = 0x1000000; // for bit 24
74 |
75 | var timestamp = Environment.TickCount;
76 |
77 | var flags = (uint) lParam.ToInt64();
78 |
79 | //bit 30 Specifies the previous key state. The value is 1 if the key is down before the message is sent; it is 0 if the key is up.
80 | var wasKeyDown = (flags & maskKeydown) > 0;
81 | //bit 31 Specifies the transition state. The value is 0 if the key is being pressed and 1 if it is being released.
82 | var isKeyReleased = (flags & maskKeyup) > 0;
83 | //bit 24 Specifies the extended key state. The value is 1 if the key is an extended key, otherwise the value is 0.
84 | var isExtendedKey = (flags & maskExtendedKey) > 0;
85 |
86 |
87 | var keyData = AppendModifierStates((Keys) wParam);
88 | var scanCode = (int) (((flags & 0x10000) | (flags & 0x20000) | (flags & 0x40000) | (flags & 0x80000) |
89 | (flags & 0x100000) | (flags & 0x200000) | (flags & 0x400000) | (flags & 0x800000)) >>
90 | 16);
91 |
92 | var isKeyDown = !isKeyReleased;
93 | var isKeyUp = wasKeyDown && isKeyReleased;
94 |
95 | return new KeyEventArgsExt(keyData, scanCode, timestamp, isKeyDown, isKeyUp, isExtendedKey);
96 | }
97 |
98 | internal static KeyEventArgsExt FromRawDataGlobal(CallbackData data)
99 | {
100 | var wParam = data.WParam;
101 | var lParam = data.LParam;
102 | var keyboardHookStruct =
103 | (KeyboardHookStruct) Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
104 |
105 | var keyData = AppendModifierStates((Keys) keyboardHookStruct.VirtualKeyCode);
106 |
107 | var keyCode = (int) wParam;
108 | var isKeyDown = keyCode == Messages.WM_KEYDOWN || keyCode == Messages.WM_SYSKEYDOWN;
109 | var isKeyUp = keyCode == Messages.WM_KEYUP || keyCode == Messages.WM_SYSKEYUP;
110 |
111 | const uint maskExtendedKey = 0x1;
112 | var isExtendedKey = (keyboardHookStruct.Flags & maskExtendedKey) > 0;
113 |
114 | return new KeyEventArgsExt(keyData, keyboardHookStruct.ScanCode, keyboardHookStruct.Time, isKeyDown,
115 | isKeyUp, isExtendedKey);
116 | }
117 |
118 | // # It is not possible to distinguish Keys.LControlKey and Keys.RControlKey when they are modifiers
119 | // Check for Keys.Control instead
120 | // Same for Shift and Alt(Menu)
121 | // See more at http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.windowsforms/2008-04/msg00127.html #
122 |
123 | // A shortcut to make life easier
124 | private static bool CheckModifier(int vKey)
125 | {
126 | return (KeyboardNativeMethods.GetKeyState(vKey) & 0x8000) > 0;
127 | }
128 |
129 | private static Keys AppendModifierStates(Keys keyData)
130 | {
131 | // Is Control being held down?
132 | var control = CheckModifier(KeyboardNativeMethods.VK_CONTROL);
133 | // Is Shift being held down?
134 | var shift = CheckModifier(KeyboardNativeMethods.VK_SHIFT);
135 | // Is Alt being held down?
136 | var alt = CheckModifier(KeyboardNativeMethods.VK_MENU);
137 |
138 | // Windows keys
139 | // # combine LWin and RWin key with other keys will potentially corrupt the data
140 | // notable F5 | Keys.LWin == F12, see https://globalmousekeyhook.codeplex.com/workitem/1188
141 | // and the KeyEventArgs.KeyData don't recognize combined data either
142 |
143 | // Function (Fn) key
144 | // # CANNOT determine state due to conversion inside keyboard
145 | // See http://en.wikipedia.org/wiki/Fn_key#Technical_details #
146 |
147 | return keyData |
148 | (control ? Keys.Control : Keys.None) |
149 | (shift ? Keys.Shift : Keys.None) |
150 | (alt ? Keys.Alt : Keys.None);
151 | }
152 | }
153 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 |
56 | # StyleCop
57 | StyleCopReport.xml
58 |
59 | # Files built by Visual Studio
60 | *_i.c
61 | *_p.c
62 | *_i.h
63 | *.ilk
64 | *.meta
65 | *.obj
66 | *.iobj
67 | *.pch
68 | *.pdb
69 | *.ipdb
70 | *.pgc
71 | *.pgd
72 | *.rsp
73 | *.sbr
74 | *.tlb
75 | *.tli
76 | *.tlh
77 | *.tmp
78 | *.tmp_proj
79 | *.log
80 | *.vspscc
81 | *.vssscc
82 | .builds
83 | *.pidb
84 | *.svclog
85 | *.scc
86 |
87 | # Chutzpah Test files
88 | _Chutzpah*
89 |
90 | # Visual C++ cache files
91 | ipch/
92 | *.aps
93 | *.ncb
94 | *.opendb
95 | *.opensdf
96 | *.sdf
97 | *.cachefile
98 | *.VC.db
99 | *.VC.VC.opendb
100 |
101 | # Visual Studio profiler
102 | *.psess
103 | *.vsp
104 | *.vspx
105 | *.sap
106 |
107 | # Visual Studio Trace Files
108 | *.e2e
109 |
110 | # TFS 2012 Local Workspace
111 | $tf/
112 |
113 | # Guidance Automation Toolkit
114 | *.gpState
115 |
116 | # ReSharper is a .NET coding add-in
117 | _ReSharper*/
118 | *.[Rr]e[Ss]harper
119 | *.DotSettings.user
120 |
121 | # JustCode is a .NET coding add-in
122 | .JustCode
123 |
124 | # TeamCity is a build add-in
125 | _TeamCity*
126 |
127 | # DotCover is a Code Coverage Tool
128 | *.dotCover
129 |
130 | # AxoCover is a Code Coverage Tool
131 | .axoCover/*
132 | !.axoCover/settings.json
133 |
134 | # Visual Studio code coverage results
135 | *.coverage
136 | *.coveragexml
137 |
138 | # NCrunch
139 | _NCrunch_*
140 | .*crunch*.local.xml
141 | nCrunchTemp_*
142 |
143 | # MightyMoose
144 | *.mm.*
145 | AutoTest.Net/
146 |
147 | # Web workbench (sass)
148 | .sass-cache/
149 |
150 | # Installshield output folder
151 | [Ee]xpress/
152 |
153 | # DocProject is a documentation generator add-in
154 | DocProject/buildhelp/
155 | DocProject/Help/*.HxT
156 | DocProject/Help/*.HxC
157 | DocProject/Help/*.hhc
158 | DocProject/Help/*.hhk
159 | DocProject/Help/*.hhp
160 | DocProject/Help/Html2
161 | DocProject/Help/html
162 |
163 | # Click-Once directory
164 | publish/
165 |
166 | # Publish Web Output
167 | *.[Pp]ublish.xml
168 | *.azurePubxml
169 | # Note: Comment the next line if you want to checkin your web deploy settings,
170 | # but database connection strings (with potential passwords) will be unencrypted
171 | *.pubxml
172 | *.publishproj
173 |
174 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
175 | # checkin your Azure Web App publish settings, but sensitive information contained
176 | # in these scripts will be unencrypted
177 | PublishScripts/
178 |
179 | # NuGet Packages
180 | *.nupkg
181 | # The packages folder can be ignored because of Package Restore
182 | **/[Pp]ackages/*
183 | # except build/, which is used as an MSBuild target.
184 | !**/[Pp]ackages/build/
185 | # Uncomment if necessary however generally it will be regenerated when needed
186 | #!**/[Pp]ackages/repositories.config
187 | # NuGet v3's project.json files produces more ignorable files
188 | *.nuget.props
189 | *.nuget.targets
190 |
191 | # Microsoft Azure Build Output
192 | csx/
193 | *.build.csdef
194 |
195 | # Microsoft Azure Emulator
196 | ecf/
197 | rcf/
198 |
199 | # Windows Store app package directories and files
200 | AppPackages/
201 | BundleArtifacts/
202 | Package.StoreAssociation.xml
203 | _pkginfo.txt
204 | *.appx
205 |
206 | # Visual Studio cache files
207 | # files ending in .cache can be ignored
208 | *.[Cc]ache
209 | # but keep track of directories ending in .cache
210 | !*.[Cc]ache/
211 |
212 | # Others
213 | ClientBin/
214 | ~$*
215 | *~
216 | *.dbmdl
217 | *.dbproj.schemaview
218 | *.jfm
219 | *.pfx
220 | *.publishsettings
221 | orleans.codegen.cs
222 |
223 | # Including strong name files can present a security risk
224 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
225 | #*.snk
226 |
227 | # Since there are multiple workflows, uncomment next line to ignore bower_components
228 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
229 | #bower_components/
230 |
231 | # RIA/Silverlight projects
232 | Generated_Code/
233 |
234 | # Backup & report files from converting an old project file
235 | # to a newer Visual Studio version. Backup files are not needed,
236 | # because we have git ;-)
237 | _UpgradeReport_Files/
238 | Backup*/
239 | UpgradeLog*.XML
240 | UpgradeLog*.htm
241 | ServiceFabricBackup/
242 | *.rptproj.bak
243 |
244 | # SQL Server files
245 | *.mdf
246 | *.ldf
247 | *.ndf
248 |
249 | # Business Intelligence projects
250 | *.rdl.data
251 | *.bim.layout
252 | *.bim_*.settings
253 | *.rptproj.rsuser
254 |
255 | # Microsoft Fakes
256 | FakesAssemblies/
257 |
258 | # GhostDoc plugin setting file
259 | *.GhostDoc.xml
260 |
261 | # Node.js Tools for Visual Studio
262 | .ntvs_analysis.dat
263 | node_modules/
264 |
265 | # Visual Studio 6 build log
266 | *.plg
267 |
268 | # Visual Studio 6 workspace options file
269 | *.opt
270 |
271 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
272 | *.vbw
273 |
274 | # Visual Studio LightSwitch build output
275 | **/*.HTMLClient/GeneratedArtifacts
276 | **/*.DesktopClient/GeneratedArtifacts
277 | **/*.DesktopClient/ModelManifest.xml
278 | **/*.Server/GeneratedArtifacts
279 | **/*.Server/ModelManifest.xml
280 | _Pvt_Extensions
281 |
282 | # Paket dependency manager
283 | .paket/paket.exe
284 | paket-files/
285 |
286 | # FAKE - F# Make
287 | .fake/
288 |
289 | # JetBrains Rider
290 | .idea/
291 | *.sln.iml
292 |
293 | # CodeRush
294 | .cr/
295 |
296 | # Python Tools for Visual Studio (PTVS)
297 | __pycache__/
298 | *.pyc
299 |
300 | # Cake - Uncomment if you are using it
301 | # tools/**
302 | # !tools/packages.config
303 |
304 | # Tabs Studio
305 | *.tss
306 |
307 | # Telerik's JustMock configuration file
308 | *.jmconfig
309 |
310 | # BizTalk build output
311 | *.btp.cs
312 | *.btm.cs
313 | *.odx.cs
314 | *.xsd.cs
315 |
316 | # OpenCover UI analysis results
317 | OpenCover/
318 |
319 | # Azure Stream Analytics local run output
320 | ASALocalRun/
321 |
322 | # MSBuild Binary and Structured Log
323 | *.binlog
324 |
325 | # NVidia Nsight GPU debugger configuration file
326 | *.nvuser
327 |
328 | # MFractors (Xamarin productivity tool) working folder
329 | .mfractor/
--------------------------------------------------------------------------------
/Autofarmer/Autofarm.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | 15, 21
122 |
123 |
124 | True
125 |
126 |
127 | True
128 |
129 |
130 | True
131 |
132 |
133 | True
134 |
135 |
136 | True
137 |
138 |
139 | 151, 21
140 |
141 |
--------------------------------------------------------------------------------
/Autofarmer/Autofarmer.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {55F3DB6F-FA3A-493D-8FDC-88404C7CC89D}
8 | WinExe
9 | Properties
10 | Autofarmer
11 | Autofarmer
12 | v4.5.2
13 | 512
14 | true
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | Form
51 |
52 |
53 | Autofarm.cs
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 | Form
106 |
107 |
108 |
109 |
110 | Autofarm.cs
111 |
112 |
113 | ResXFileCodeGenerator
114 | Resources.Designer.cs
115 | Designer
116 |
117 |
118 | True
119 | Resources.resx
120 |
121 |
122 |
123 | SettingsSingleFileGenerator
124 | Settings.Designer.cs
125 |
126 |
127 | True
128 | Settings.settings
129 | True
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
147 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/MouseEventExtArgs.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 | using System.Windows.Forms;
8 | using Gma.System.MouseKeyHook.WinApi;
9 |
10 | namespace Gma.System.MouseKeyHook
11 | {
12 | ///
13 | /// Provides extended data for the MouseClickExt and MouseMoveExt events.
14 | ///
15 | public class MouseEventExtArgs : MouseEventArgs
16 | {
17 | ///
18 | /// Initializes a new instance of the class.
19 | ///
20 | /// One of the MouseButtons values indicating which mouse button was pressed.
21 | /// The number of times a mouse button was pressed.
22 | /// The x and y coordinate of a mouse click, in pixels.
23 | /// A signed count of the number of detents the wheel has rotated.
24 | /// The system tick count when the event occurred.
25 | /// True if event signals mouse button down.
26 | /// True if event signals mouse button up.
27 | internal MouseEventExtArgs(MouseButtons buttons, int clicks, Point point, int delta, int timestamp,
28 | bool isMouseButtonDown, bool isMouseButtonUp)
29 | : base(buttons, clicks, point.X, point.Y, delta)
30 | {
31 | IsMouseButtonDown = isMouseButtonDown;
32 | IsMouseButtonUp = isMouseButtonUp;
33 | Timestamp = timestamp;
34 | }
35 |
36 | ///
37 | /// Set this property to true inside your event handler to prevent further processing of the event in other
38 | /// applications.
39 | ///
40 | public bool Handled { get; set; }
41 |
42 | ///
43 | /// True if event contains information about wheel scroll.
44 | ///
45 | public bool WheelScrolled
46 | {
47 | get { return Delta != 0; }
48 | }
49 |
50 | ///
51 | /// True if event signals a click. False if it was only a move or wheel scroll.
52 | ///
53 | public bool Clicked
54 | {
55 | get { return Clicks > 0; }
56 | }
57 |
58 | ///
59 | /// True if event signals mouse button down.
60 | ///
61 | public bool IsMouseButtonDown { get; }
62 |
63 | ///
64 | /// True if event signals mouse button up.
65 | ///
66 | public bool IsMouseButtonUp { get; }
67 |
68 | ///
69 | /// The system tick count of when the event occurred.
70 | ///
71 | public int Timestamp { get; }
72 |
73 | ///
74 | ///
75 | internal Point Point
76 | {
77 | get { return new Point(X, Y); }
78 | }
79 |
80 | internal static MouseEventExtArgs FromRawDataApp(CallbackData data)
81 | {
82 | var wParam = data.WParam;
83 | var lParam = data.LParam;
84 |
85 | var marshalledMouseStruct =
86 | (AppMouseStruct) Marshal.PtrToStructure(lParam, typeof(AppMouseStruct));
87 | return FromRawDataUniversal(wParam, marshalledMouseStruct.ToMouseStruct());
88 | }
89 |
90 | internal static MouseEventExtArgs FromRawDataGlobal(CallbackData data)
91 | {
92 | var wParam = data.WParam;
93 | var lParam = data.LParam;
94 |
95 | var marshalledMouseStruct = (MouseStruct) Marshal.PtrToStructure(lParam, typeof(MouseStruct));
96 | return FromRawDataUniversal(wParam, marshalledMouseStruct);
97 | }
98 |
99 | ///
100 | /// Creates from relevant mouse data.
101 | ///
102 | /// First Windows Message parameter.
103 | /// A MouseStruct containing information from which to construct MouseEventExtArgs.
104 | /// A new MouseEventExtArgs object.
105 | private static MouseEventExtArgs FromRawDataUniversal(IntPtr wParam, MouseStruct mouseInfo)
106 | {
107 | var button = MouseButtons.None;
108 | short mouseDelta = 0;
109 | var clickCount = 0;
110 |
111 | var isMouseButtonDown = false;
112 | var isMouseButtonUp = false;
113 |
114 |
115 | switch ((long) wParam)
116 | {
117 | case Messages.WM_LBUTTONDOWN:
118 | isMouseButtonDown = true;
119 | button = MouseButtons.Left;
120 | clickCount = 1;
121 | break;
122 | case Messages.WM_LBUTTONUP:
123 | isMouseButtonUp = true;
124 | button = MouseButtons.Left;
125 | clickCount = 1;
126 | break;
127 | case Messages.WM_LBUTTONDBLCLK:
128 | isMouseButtonDown = true;
129 | button = MouseButtons.Left;
130 | clickCount = 2;
131 | break;
132 | case Messages.WM_RBUTTONDOWN:
133 | isMouseButtonDown = true;
134 | button = MouseButtons.Right;
135 | clickCount = 1;
136 | break;
137 | case Messages.WM_RBUTTONUP:
138 | isMouseButtonUp = true;
139 | button = MouseButtons.Right;
140 | clickCount = 1;
141 | break;
142 | case Messages.WM_RBUTTONDBLCLK:
143 | isMouseButtonDown = true;
144 | button = MouseButtons.Right;
145 | clickCount = 2;
146 | break;
147 | case Messages.WM_MBUTTONDOWN:
148 | isMouseButtonDown = true;
149 | button = MouseButtons.Middle;
150 | clickCount = 1;
151 | break;
152 | case Messages.WM_MBUTTONUP:
153 | isMouseButtonUp = true;
154 | button = MouseButtons.Middle;
155 | clickCount = 1;
156 | break;
157 | case Messages.WM_MBUTTONDBLCLK:
158 | isMouseButtonDown = true;
159 | button = MouseButtons.Middle;
160 | clickCount = 2;
161 | break;
162 | case Messages.WM_MOUSEWHEEL:
163 | mouseDelta = mouseInfo.MouseData;
164 | break;
165 | case Messages.WM_XBUTTONDOWN:
166 | button = mouseInfo.MouseData == 1
167 | ? MouseButtons.XButton1
168 | : MouseButtons.XButton2;
169 | isMouseButtonDown = true;
170 | clickCount = 1;
171 | break;
172 |
173 | case Messages.WM_XBUTTONUP:
174 | button = mouseInfo.MouseData == 1
175 | ? MouseButtons.XButton1
176 | : MouseButtons.XButton2;
177 | isMouseButtonUp = true;
178 | clickCount = 1;
179 | break;
180 |
181 | case Messages.WM_XBUTTONDBLCLK:
182 | isMouseButtonDown = true;
183 | button = mouseInfo.MouseData == 1
184 | ? MouseButtons.XButton1
185 | : MouseButtons.XButton2;
186 | clickCount = 2;
187 | break;
188 |
189 | case Messages.WM_MOUSEHWHEEL:
190 | mouseDelta = mouseInfo.MouseData;
191 | break;
192 | }
193 |
194 | var e = new MouseEventExtArgs(
195 | button,
196 | clickCount,
197 | mouseInfo.Point,
198 | mouseDelta,
199 | mouseInfo.Timestamp,
200 | isMouseButtonDown,
201 | isMouseButtonUp);
202 |
203 | return e;
204 | }
205 |
206 | internal MouseEventExtArgs ToDoubleClickEventArgs()
207 | {
208 | return new MouseEventExtArgs(Button, 2, Point, Delta, Timestamp, IsMouseButtonDown, IsMouseButtonUp);
209 | }
210 | }
211 | }
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/Implementation/MouseListener.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Runtime.InteropServices;
7 | using System.Windows.Forms;
8 | using Gma.System.MouseKeyHook.WinApi;
9 |
10 | namespace Gma.System.MouseKeyHook.Implementation
11 | {
12 | // Because it is a P/Invoke method, 'GetSystemMetrics(int)'
13 | // should be defined in a class named NativeMethods, SafeNativeMethods,
14 | // or UnsafeNativeMethods.
15 | // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
16 | internal static class NativeMethods
17 | {
18 | private const int SM_CXDRAG = 68;
19 | private const int SM_CYDRAG = 69;
20 |
21 | [DllImport("user32.dll")]
22 | private static extern int GetSystemMetrics(int index);
23 |
24 | public static int GetXDragThreshold()
25 | {
26 | return GetSystemMetrics(SM_CXDRAG);
27 | }
28 |
29 | public static int GetYDragThreshold()
30 | {
31 | return GetSystemMetrics(SM_CYDRAG);
32 | }
33 | }
34 |
35 | internal abstract class MouseListener : BaseListener, IMouseEvents
36 | {
37 | private readonly ButtonSet m_DoubleDown;
38 | private readonly ButtonSet m_SingleDown;
39 | private readonly Point m_UninitialisedPoint = new Point(-1, -1);
40 | private readonly int m_xDragThreshold;
41 | private readonly int m_yDragThreshold;
42 | private Point m_DragStartPosition;
43 |
44 | private bool m_IsDragging;
45 |
46 | private Point m_PreviousPosition;
47 |
48 | protected MouseListener(Subscribe subscribe)
49 | : base(subscribe)
50 | {
51 | m_xDragThreshold = NativeMethods.GetXDragThreshold();
52 | m_yDragThreshold = NativeMethods.GetYDragThreshold();
53 | m_IsDragging = false;
54 |
55 | m_PreviousPosition = m_UninitialisedPoint;
56 | m_DragStartPosition = m_UninitialisedPoint;
57 |
58 | m_DoubleDown = new ButtonSet();
59 | m_SingleDown = new ButtonSet();
60 | }
61 |
62 | public event MouseEventHandler MouseMove;
63 | public event EventHandler MouseMoveExt;
64 | public event MouseEventHandler MouseClick;
65 | public event MouseEventHandler MouseDown;
66 | public event EventHandler MouseDownExt;
67 | public event MouseEventHandler MouseUp;
68 | public event EventHandler MouseUpExt;
69 | public event MouseEventHandler MouseWheel;
70 | public event EventHandler MouseWheelExt;
71 | public event MouseEventHandler MouseDoubleClick;
72 | public event MouseEventHandler MouseDragStarted;
73 | public event EventHandler MouseDragStartedExt;
74 | public event MouseEventHandler MouseDragFinished;
75 | public event EventHandler MouseDragFinishedExt;
76 |
77 | protected override bool Callback(CallbackData data)
78 | {
79 | var e = GetEventArgs(data);
80 |
81 | if (e.IsMouseButtonDown)
82 | ProcessDown(ref e);
83 |
84 | if (e.IsMouseButtonUp)
85 | ProcessUp(ref e);
86 |
87 | if (e.WheelScrolled)
88 | ProcessWheel(ref e);
89 |
90 | if (HasMoved(e.Point))
91 | ProcessMove(ref e);
92 |
93 | ProcessDrag(ref e);
94 |
95 | return !e.Handled;
96 | }
97 |
98 | protected abstract MouseEventExtArgs GetEventArgs(CallbackData data);
99 |
100 | protected virtual void ProcessWheel(ref MouseEventExtArgs e)
101 | {
102 | OnWheel(e);
103 | OnWheelExt(e);
104 | }
105 |
106 | protected virtual void ProcessDown(ref MouseEventExtArgs e)
107 | {
108 | OnDown(e);
109 | OnDownExt(e);
110 | if (e.Handled)
111 | return;
112 |
113 | if (e.Clicks == 2)
114 | m_DoubleDown.Add(e.Button);
115 |
116 | if (e.Clicks == 1)
117 | m_SingleDown.Add(e.Button);
118 | }
119 |
120 | protected virtual void ProcessUp(ref MouseEventExtArgs e)
121 | {
122 | OnUp(e);
123 | OnUpExt(e);
124 | if (e.Handled)
125 | return;
126 |
127 | if (m_SingleDown.Contains(e.Button))
128 | {
129 | OnClick(e);
130 | m_SingleDown.Remove(e.Button);
131 | }
132 |
133 | if (m_DoubleDown.Contains(e.Button))
134 | {
135 | e = e.ToDoubleClickEventArgs();
136 | OnDoubleClick(e);
137 | m_DoubleDown.Remove(e.Button);
138 | }
139 | }
140 |
141 | private void ProcessMove(ref MouseEventExtArgs e)
142 | {
143 | m_PreviousPosition = e.Point;
144 |
145 | OnMove(e);
146 | OnMoveExt(e);
147 | }
148 |
149 | private void ProcessDrag(ref MouseEventExtArgs e)
150 | {
151 | if (m_SingleDown.Contains(MouseButtons.Left))
152 | {
153 | if (m_DragStartPosition.Equals(m_UninitialisedPoint))
154 | m_DragStartPosition = e.Point;
155 |
156 | ProcessDragStarted(ref e);
157 | }
158 | else
159 | {
160 | m_DragStartPosition = m_UninitialisedPoint;
161 | ProcessDragFinished(ref e);
162 | }
163 | }
164 |
165 | private void ProcessDragStarted(ref MouseEventExtArgs e)
166 | {
167 | if (!m_IsDragging)
168 | {
169 | var isXDragging = Math.Abs(e.Point.X - m_DragStartPosition.X) > m_xDragThreshold;
170 | var isYDragging = Math.Abs(e.Point.Y - m_DragStartPosition.Y) > m_yDragThreshold;
171 | m_IsDragging = isXDragging || isYDragging;
172 |
173 | if (m_IsDragging)
174 | {
175 | OnDragStarted(e);
176 | OnDragStartedExt(e);
177 | }
178 | }
179 | }
180 |
181 | private void ProcessDragFinished(ref MouseEventExtArgs e)
182 | {
183 | if (m_IsDragging)
184 | {
185 | OnDragFinished(e);
186 | OnDragFinishedExt(e);
187 | m_IsDragging = false;
188 | }
189 | }
190 |
191 | private bool HasMoved(Point actualPoint)
192 | {
193 | return m_PreviousPosition != actualPoint;
194 | }
195 |
196 | protected virtual void OnMove(MouseEventArgs e)
197 | {
198 | var handler = MouseMove;
199 | if (handler != null) handler(this, e);
200 | }
201 |
202 | protected virtual void OnMoveExt(MouseEventExtArgs e)
203 | {
204 | var handler = MouseMoveExt;
205 | if (handler != null) handler(this, e);
206 | }
207 |
208 | protected virtual void OnClick(MouseEventArgs e)
209 | {
210 | var handler = MouseClick;
211 | if (handler != null) handler(this, e);
212 | }
213 |
214 | protected virtual void OnDown(MouseEventArgs e)
215 | {
216 | var handler = MouseDown;
217 | if (handler != null) handler(this, e);
218 | }
219 |
220 | protected virtual void OnDownExt(MouseEventExtArgs e)
221 | {
222 | var handler = MouseDownExt;
223 | if (handler != null) handler(this, e);
224 | }
225 |
226 | protected virtual void OnUp(MouseEventArgs e)
227 | {
228 | var handler = MouseUp;
229 | if (handler != null) handler(this, e);
230 | }
231 |
232 | protected virtual void OnUpExt(MouseEventExtArgs e)
233 | {
234 | var handler = MouseUpExt;
235 | if (handler != null) handler(this, e);
236 | }
237 |
238 | protected virtual void OnWheel(MouseEventArgs e)
239 | {
240 | var handler = MouseWheel;
241 | if (handler != null) handler(this, e);
242 | }
243 |
244 | protected virtual void OnWheelExt(MouseEventExtArgs e)
245 | {
246 | var handler = MouseWheelExt;
247 | if (handler != null) handler(this, e);
248 | }
249 |
250 | protected virtual void OnDoubleClick(MouseEventArgs e)
251 | {
252 | var handler = MouseDoubleClick;
253 | if (handler != null) handler(this, e);
254 | }
255 |
256 | protected virtual void OnDragStarted(MouseEventArgs e)
257 | {
258 | var handler = MouseDragStarted;
259 | if (handler != null) handler(this, e);
260 | }
261 |
262 | protected virtual void OnDragStartedExt(MouseEventExtArgs e)
263 | {
264 | var handler = MouseDragStartedExt;
265 | if (handler != null) handler(this, e);
266 | }
267 |
268 | protected virtual void OnDragFinished(MouseEventArgs e)
269 | {
270 | var handler = MouseDragFinished;
271 | if (handler != null) handler(this, e);
272 | }
273 |
274 | protected virtual void OnDragFinishedExt(MouseEventExtArgs e)
275 | {
276 | var handler = MouseDragFinishedExt;
277 | if (handler != null) handler(this, e);
278 | }
279 | }
280 | }
--------------------------------------------------------------------------------
/Autofarmer/globalKeyboardHook.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Runtime.InteropServices;
5 | using System.Windows.Forms;
6 |
7 | // Based on globalKeyboardHook.cs : https://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook
8 |
9 | namespace Autofarmer {
10 | ///
11 | /// A class that manages a global low level keyboard hook
12 | ///
13 | class GlobalKeyboardHook {
14 | #region Constant, Structure and Delegate Definitions
15 | ///
16 | /// defines the callback type for the hook
17 | ///
18 | public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);
19 |
20 | public struct keyboardHookStruct {
21 | public int vkCode;
22 | public int scanCode;
23 | public int flags;
24 | public int time;
25 | public int dwExtraInfo;
26 | }
27 |
28 | const int WH_KEYBOARD_LL = 13;
29 | const int WM_KEYDOWN = 0x100;
30 | const int WM_KEYUP = 0x101;
31 | const int WM_SYSKEYDOWN = 0x104;
32 | const int WM_SYSKEYUP = 0x105;
33 | #endregion
34 |
35 | #region Instance Variables
36 | ///
37 | /// The collections of keys to watch for
38 | ///
39 | public List HookedKeys = new List();
40 | ///
41 | /// Handle to the hook, need this to unhook and call the next hook
42 | ///
43 | IntPtr hhook = IntPtr.Zero;
44 | private keyboardHookProc hookProcDelegate;
45 | #endregion
46 |
47 | #region Events
48 | ///
49 | /// Occurs when one of the hooked keys is pressed
50 | ///
51 | public event KeyEventHandler KeyDown;
52 | ///
53 | /// Occurs when one of the hooked keys is released
54 | ///
55 | public event KeyEventHandler KeyUp;
56 | #endregion
57 |
58 | #region Constructors and Destructors
59 | ///
60 | /// Initializes a new instance of the class and installs the keyboard hook.
61 | ///
62 | public GlobalKeyboardHook() {
63 | hookProcDelegate = hookProc;
64 | hook();
65 | }
66 |
67 | ///
68 | /// Releases unmanaged resources and performs other cleanup operations before the
69 | /// is reclaimed by garbage collection and uninstalls the keyboard hook.
70 | ///
71 | ~GlobalKeyboardHook() {
72 | unhook();
73 | }
74 | #endregion
75 |
76 | #region Public Methods
77 | ///
78 | /// Installs the global hook
79 | ///
80 | public void hook() {
81 | IntPtr hInstance = LoadLibrary("User32");
82 | hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProcDelegate, hInstance, 0);
83 | }
84 |
85 | ///
86 | /// Uninstalls the global hook
87 | ///
88 | public void unhook() {
89 | Console.WriteLine("Unhooking.");
90 | UnhookWindowsHookEx(hhook);
91 | }
92 |
93 | ///
94 | /// The callback for the keyboard hook
95 | ///
96 | /// The hook code, if it isn't >= 0, the function shouldn't do anyting
97 | /// The event type
98 | /// The keyhook event information
99 | ///
100 | public int hookProc(int code, int wParam, ref keyboardHookStruct lParam) {
101 | if (code >= 0) {
102 | Keys key = (Keys)lParam.vkCode;
103 | KeyEventArgs kea = new KeyEventArgs(key);
104 | if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null)) {
105 | KeyDown(this, kea);
106 | } else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null)) {
107 | KeyUp(this, kea);
108 | }
109 | if (kea.Handled)
110 | return 1;
111 | }
112 | return CallNextHookEx(hhook, code, wParam, ref lParam);
113 | }
114 | #endregion
115 |
116 | #region DLL imports
117 | ///
118 | /// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null
119 | ///
120 | /// The id of the event you want to hook
121 | /// The callback.
122 | /// The handle you want to attach the event to, can be null
123 | /// The thread you want to attach the event to, can be null
124 | /// a handle to the desired hook
125 | [DllImport("user32.dll")]
126 | static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
127 |
128 | ///
129 | /// Unhooks the windows hook.
130 | ///
131 | /// The hook handle that was returned from SetWindowsHookEx
132 | /// True if successful, false otherwise
133 | [DllImport("user32.dll")]
134 | static extern bool UnhookWindowsHookEx(IntPtr hInstance);
135 |
136 | ///
137 | /// Calls the next hook.
138 | ///
139 | /// The hook id
140 | /// The hook code
141 | /// The wparam.
142 | /// The lparam.
143 | ///
144 | [DllImport("user32.dll")]
145 | static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);
146 |
147 | ///
148 | /// Loads the library.
149 | ///
150 | /// Name of the library
151 | /// A handle to the library
152 | [DllImport("kernel32.dll")]
153 | static extern IntPtr LoadLibrary(string lpFileName);
154 | #endregion
155 | }
156 | }
157 |
158 |
159 | /*using System;
160 | using System.Collections.Generic;
161 | using System.Text;
162 | using System.Runtime.InteropServices;
163 | using System.Windows.Forms;
164 |
165 | // codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook
166 | // Modified for Personal Use
167 |
168 | namespace Utilities {
169 | class globalKeyboardHook {
170 | #region Constant, Structure and Delegate Definitions
171 | public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);
172 |
173 | public struct keyboardHookStruct {
174 | public int vkCode;
175 | public int scanCode;
176 | public int flags;
177 | public int time;
178 | public int dwExtraInfo;
179 | }
180 |
181 | const int WH_KEYBOARD_LL = 13;
182 | const int WM_KEYDOWN = 0x100;
183 | const int WM_KEYUP = 0x101;
184 | const int WM_SYSKEYDOWN = 0x104;
185 | const int WM_SYSKEYUP = 0x105;
186 | #endregion
187 |
188 | #region Instance Variables
189 | // The collections of keys to watch for
190 | public List HookedKeys = new List();
191 | // Handle to the hook, need this to unhook and call the next hook
192 | IntPtr hhook = IntPtr.Zero;
193 | #endregion
194 |
195 | #region Events
196 | // Occurs when one of the hooked keys is pressed
197 | public event KeyEventHandler KeyDown;
198 | // Occurs when one of the hooked keys is released
199 | public event KeyEventHandler KeyUp;
200 | #endregion
201 |
202 | #region Constructors and Destructors
203 | // Initializes a new instance of the class and installs the keyboard hook.
204 | public globalKeyboardHook() {
205 | hook();
206 | }
207 |
208 | // Releases unmanaged resources and performs other cleanup operations before the
209 | // is reclaimed by garbage collection and uninstalls the keyboard hook.
210 | ~globalKeyboardHook() {
211 | unhook();
212 | }
213 | #endregion
214 |
215 | #region Public Methods
216 | // Installs the global hook
217 | public void hook() {
218 | IntPtr hInstance = LoadLibrary("User32");
219 | hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, hInstance, 0);
220 | }
221 | // Uninstalls the global hook
222 | public void unhook() {
223 | UnhookWindowsHookEx(hhook);
224 | }
225 |
226 | ///
227 | /// The callback for the keyboard hook
228 | ///
229 | /// The hook code, if it isn't >= 0, the function shouldn't do anyting
230 | /// The event type
231 | /// The keyhook event information
232 | ///
233 | public int hookProc(int code, int wParam, ref keyboardHookStruct lParam) {
234 | if (code >= 0) {
235 | Keys key = (Keys)lParam.vkCode;
236 | // We use this if we want to limit the collected keys:
237 | // if (HookedKeys.Contains(key)) {
238 | KeyEventArgs kea = new KeyEventArgs(key);
239 | if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null)) {
240 | KeyDown(this, kea);
241 | } else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null)) {
242 | KeyUp(this, kea);
243 | }
244 | if (kea.Handled)
245 | return 1;
246 | }
247 | return CallNextHookEx(hhook, code, wParam, ref lParam);
248 | }
249 | #endregion
250 |
251 | #region DLL imports
252 | ///
253 | /// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null
254 | ///
255 | /// The id of the event you want to hook
256 | /// The callback.
257 | /// The handle you want to attach the event to, can be null
258 | /// The thread you want to attach the event to, can be null
259 | /// a handle to the desired hook
260 | [DllImport("user32.dll")]
261 | static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
262 |
263 | ///
264 | /// Unhooks the windows hook.
265 | ///
266 | /// The hook handle that was returned from SetWindowsHookEx
267 | /// True if successful, false otherwise
268 | [DllImport("user32.dll")]
269 | static extern bool UnhookWindowsHookEx(IntPtr hInstance);
270 |
271 | ///
272 | /// Calls the next hook.
273 | ///
274 | /// The hook id
275 | /// The hook code
276 | /// The wparam.
277 | /// The lparam.
278 | ///
279 | [DllImport("user32.dll")]
280 | static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);
281 |
282 | ///
283 | /// Loads the library.
284 | ///
285 | /// Name of the library
286 | /// A handle to the library
287 | [DllImport("kernel32.dll")]
288 | static extern IntPtr LoadLibrary(string lpFileName);
289 | #endregion
290 | }
291 | }*/
292 |
--------------------------------------------------------------------------------
/Autofarmer/MouseKeyHook/HotKeys/HotKeySet.cs:
--------------------------------------------------------------------------------
1 | // This code is distributed under MIT license.
2 | // Copyright (c) 2015 George Mamaladze
3 | // See license.txt or https://mit-license.org/
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Windows.Forms;
8 | using Gma.System.MouseKeyHook.Implementation;
9 |
10 | namespace Gma.System.MouseKeyHook.HotKeys
11 | {
12 | ///
13 | /// An immutable set of Hot Keys that provides an event for when the set is activated.
14 | ///
15 | public class HotKeySet
16 | {
17 | ///
18 | /// A delegate representing the signature for the OnHotKeysDownHold event
19 | ///
20 | ///
21 | ///
22 | public delegate void HotKeyHandler(object sender, HotKeyArgs e);
23 |
24 | private readonly Dictionary m_hotkeystate; //Keeps track of the status of the set of Keys
25 |
26 | /*
27 | * Example of m_remapping:
28 | * a single key from the set of Keys requested is chosen to be the reference key (aka primary key)
29 | *
30 | * m_remapping[ Keys.LShiftKey ] = Keys.LShiftKey
31 | * m_remapping[ Keys.RShiftKey ] = Keys.LShiftKey
32 | *
33 | * This allows the m_hotkeystate to use a single key (primary key) from the set that will act on behalf of all the keys in the set,
34 | * which in turn reduces to this:
35 | *
36 | * Keys k = Keys.RShiftKey
37 | * Keys primaryKey = PrimaryKeyOf( k ) = Keys.LShiftKey
38 | * m_hotkeystate[ primaryKey ] = true/false
39 | */
40 | private readonly Dictionary m_remapping; //Used for mapping multiple keys to a single key
41 |
42 | private bool m_enabled = true; //enabled by default
43 |
44 | //These provide the actual status of whether a set is truly activated or not.
45 | private int m_hotkeydowncount; //number of hot keys down
46 |
47 | private int m_remappingCount;
48 | //the number of remappings, i.e., a set of mappings, not the individual count in m_remapping
49 |
50 | ///
51 | /// Creates an instance of the HotKeySet class. Once created, the keys cannot be changed.
52 | ///
53 | /// Set of Hot Keys
54 | public HotKeySet(IEnumerable hotkeys)
55 | {
56 | m_hotkeystate = new Dictionary();
57 | m_remapping = new Dictionary();
58 | HotKeys = hotkeys;
59 | InitializeKeys();
60 | }
61 |
62 | ///
63 | /// Enables the ability to name the set
64 | ///
65 | public string Name { get; set; }
66 |
67 | ///
68 | /// Enables the ability to describe what the set is used for or supposed to do
69 | ///
70 | public string Description { get; set; }
71 |
72 | ///
73 | /// Gets the set of hotkeys that this class handles.
74 | ///
75 | public IEnumerable HotKeys { get; }
76 |
77 | ///
78 | /// Returns whether the set of Keys is activated
79 | ///
80 | public bool HotKeysActivated
81 | {
82 | get { return m_hotkeydowncount == m_hotkeystate.Count - m_remappingCount; }
83 | }
84 |
85 | ///
86 | /// Gets or sets the enabled state of the HotKey set.
87 | ///
88 | public bool Enabled
89 | {
90 | get { return m_enabled; }
91 | set
92 | {
93 | if (value)
94 | InitializeKeys(); //must get the actual current state of each key to update
95 |
96 | m_enabled = value;
97 | }
98 | }
99 |
100 | ///
101 | /// Called as the user holds down the keys in the set. It is NOT triggered the first time the keys are set.
102 | ///
103 | ///
104 | public event HotKeyHandler OnHotKeysDownHold;
105 |
106 | ///
107 | /// Called whenever the hot key set is no longer active. This is essentially a KeyPress event, indicating that a full
108 | /// key cycle has occurred, only for HotKeys because a single key removed from the set constitutes an incomplete set.
109 | ///
110 | public event HotKeyHandler OnHotKeysUp;
111 |
112 | ///
113 | /// Called the first time the down keys are set. It does not get called throughout the duration the user holds it but
114 | /// only the
115 | /// first time it's activated.
116 | ///
117 | public event HotKeyHandler OnHotKeysDownOnce;
118 |
119 | ///
120 | /// General invocation handler
121 | ///
122 | ///
123 | private void InvokeHotKeyHandler(HotKeyHandler hotKeyDelegate)
124 | {
125 | if (hotKeyDelegate != null)
126 | hotKeyDelegate(this, new HotKeyArgs(DateTime.Now));
127 | }
128 |
129 | ///
130 | /// Adds the keys into the dictionary tracking the keys and gets the real-time status of the Keys
131 | /// from the OS
132 | ///
133 | private void InitializeKeys()
134 | {
135 | foreach (var k in HotKeys)
136 | {
137 | if (m_hotkeystate.ContainsKey(k))
138 | m_hotkeystate.Add(k, false);
139 |
140 | //assign using the current state of the keyboard
141 | m_hotkeystate[k] = KeyboardState.GetCurrent().IsDown(k);
142 | }
143 | }
144 |
145 | ///
146 | /// Unregisters a previously set exclusive or based on the primary key.
147 | ///
148 | /// Any key used in the Registration method used to create an exclusive or set
149 | ///
150 | /// True if successful. False doesn't indicate a failure to unregister, it indicates that the Key is not
151 | /// registered as an Exclusive Or key or it's not the Primary Key.
152 | ///
153 | public bool UnregisterExclusiveOrKey(Keys anyKeyInTheExclusiveOrSet)
154 | {
155 | var primaryKey = GetExclusiveOrPrimaryKey(anyKeyInTheExclusiveOrSet);
156 |
157 | if (primaryKey == Keys.None || !m_remapping.ContainsValue(primaryKey))
158 | return false;
159 |
160 | var keystoremove = new List();
161 |
162 | foreach (var pair in m_remapping)
163 | if (pair.Value == primaryKey)
164 | keystoremove.Add(pair.Key);
165 |
166 | foreach (var k in keystoremove)
167 | m_remapping.Remove(k);
168 |
169 | --m_remappingCount;
170 |
171 | return true;
172 | }
173 |
174 | ///
175 | /// Registers a group of Keys that are already part of the HotKeySet in order to provide better flexibility among keys.
176 | ///
177 | ///
178 | /// HotKeySet hks = new HotKeySet( new [] { Keys.T, Keys.LShiftKey, Keys.RShiftKey } );
179 | /// RegisterExclusiveOrKey( new [] { Keys.LShiftKey, Keys.RShiftKey } );
180 | ///
181 | /// allows either Keys.LShiftKey or Keys.RShiftKey to be combined with Keys.T.
182 | ///
183 | ///
184 | ///
185 | /// Primary key used for mapping or Keys.None on error
186 | public Keys RegisterExclusiveOrKey(IEnumerable orKeySet)
187 | {
188 | //Verification first, so as to not leave the m_remapping with a partial set.
189 | foreach (var k in orKeySet)
190 | if (!m_hotkeystate.ContainsKey(k))
191 | return Keys.None;
192 |
193 | var i = 0;
194 | var primaryKey = Keys.None;
195 |
196 | //Commit after verification
197 | foreach (var k in orKeySet)
198 | {
199 | if (i == 0)
200 | primaryKey = k;
201 |
202 | m_remapping[k] = primaryKey;
203 |
204 | ++i;
205 | }
206 |
207 | //Must increase to keep a true count of how many keys are necessary for the activation to be true
208 | ++m_remappingCount;
209 |
210 | return primaryKey;
211 | }
212 |
213 | ///
214 | /// Gets the primary key
215 | ///
216 | ///
217 | /// The primary key if it exists, otherwise Keys.None
218 | private Keys GetExclusiveOrPrimaryKey(Keys k)
219 | {
220 | return m_remapping.ContainsKey(k) ? m_remapping[k] : Keys.None;
221 | }
222 |
223 | ///
224 | /// Resolves obtaining the key used for state checking.
225 | ///
226 | ///
227 | /// The primary key if it exists, otherwise the key entered
228 | private Keys GetPrimaryKey(Keys k)
229 | {
230 | //If the key is remapped then get the primary keys
231 | return m_remapping.ContainsKey(k) ? m_remapping[k] : k;
232 | }
233 |
234 | ///
235 | ///
236 | ///
237 | internal void OnKey(KeyEventArgsExt kex)
238 | {
239 | if (!Enabled)
240 | return;
241 |
242 | //Gets the primary key if mapped to a single key or gets the key itself
243 | var primaryKey = GetPrimaryKey(kex.KeyCode);
244 |
245 | if (kex.IsKeyDown)
246 | OnKeyDown(primaryKey);
247 | else //reset
248 | OnKeyUp(primaryKey);
249 | }
250 |
251 | private void OnKeyDown(Keys k)
252 | {
253 | //If the keys are activated still then keep invoking the event
254 | if (HotKeysActivated)
255 | {
256 | InvokeHotKeyHandler(OnHotKeysDownHold); //Call the duration event
257 | }
258 |
259 | //indicates the key's state is current false but the key is now down
260 | else if (m_hotkeystate.ContainsKey(k) && !m_hotkeystate[k])
261 | {
262 | m_hotkeystate[k] = true; //key's state is down
263 | ++m_hotkeydowncount; //increase the number of keys down in this set
264 |
265 | if (HotKeysActivated) //because of the increase, check whether the set is activated
266 | InvokeHotKeyHandler(OnHotKeysDownOnce); //Call the initial event
267 | }
268 | }
269 |
270 | private void OnKeyUp(Keys k)
271 | {
272 | if (m_hotkeystate.ContainsKey(k) && m_hotkeystate[k]) //indicates the key's state was down but now it's up
273 | {
274 | var wasActive = HotKeysActivated;
275 |
276 | m_hotkeystate[k] = false; //key's state is up
277 | --m_hotkeydowncount; //this set is no longer ready
278 |
279 | if (wasActive)
280 | InvokeHotKeyHandler(OnHotKeysUp); //call the KeyUp event because the set is no longer active
281 | }
282 | }
283 | }
284 | }
--------------------------------------------------------------------------------
/KeyboardHook.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 | using System.Diagnostics;
4 |
5 | namespace GlobalLowLevelHooks {
6 | ///
7 | /// Class for intercepting low level keyboard hooks
8 | ///
9 | public class KeyboardHook {
10 | ///
11 | /// Virtual Keys
12 | ///
13 | public enum VKeys {
14 | // Losely based on http://www.pinvoke.net/default.aspx/Enums/VK.html
15 |
16 | LBUTTON = 0x01, // Left mouse button
17 | RBUTTON = 0x02, // Right mouse button
18 | CANCEL = 0x03, // Control-break processing
19 | MBUTTON = 0x04, // Middle mouse button (three-button mouse)
20 | XBUTTON1 = 0x05, // Windows 2000/XP: X1 mouse button
21 | XBUTTON2 = 0x06, // Windows 2000/XP: X2 mouse button
22 | // 0x07 // Undefined
23 | BACK = 0x08, // BACKSPACE key
24 | TAB = 0x09, // TAB key
25 | // 0x0A-0x0B, // Reserved
26 | CLEAR = 0x0C, // CLEAR key
27 | RETURN = 0x0D, // ENTER key
28 | // 0x0E-0x0F, // Undefined
29 | SHIFT = 0x10, // SHIFT key
30 | CONTROL = 0x11, // CTRL key
31 | MENU = 0x12, // ALT key
32 | PAUSE = 0x13, // PAUSE key
33 | CAPITAL = 0x14, // CAPS LOCK key
34 | KANA = 0x15, // Input Method Editor (IME) Kana mode
35 | HANGUL = 0x15, // IME Hangul mode
36 | // 0x16, // Undefined
37 | JUNJA = 0x17, // IME Junja mode
38 | FINAL = 0x18, // IME final mode
39 | HANJA = 0x19, // IME Hanja mode
40 | KANJI = 0x19, // IME Kanji mode
41 | // 0x1A, // Undefined
42 | ESCAPE = 0x1B, // ESC key
43 | CONVERT = 0x1C, // IME convert
44 | NONCONVERT = 0x1D, // IME nonconvert
45 | ACCEPT = 0x1E, // IME accept
46 | MODECHANGE = 0x1F, // IME mode change request
47 | SPACE = 0x20, // SPACEBAR
48 | PRIOR = 0x21, // PAGE UP key
49 | NEXT = 0x22, // PAGE DOWN key
50 | END = 0x23, // END key
51 | HOME = 0x24, // HOME key
52 | LEFT = 0x25, // LEFT ARROW key
53 | UP = 0x26, // UP ARROW key
54 | RIGHT = 0x27, // RIGHT ARROW key
55 | DOWN = 0x28, // DOWN ARROW key
56 | SELECT = 0x29, // SELECT key
57 | PRINT = 0x2A, // PRINT key
58 | EXECUTE = 0x2B, // EXECUTE key
59 | SNAPSHOT = 0x2C, // PRINT SCREEN key
60 | INSERT = 0x2D, // INS key
61 | DELETE = 0x2E, // DEL key
62 | HELP = 0x2F, // HELP key
63 | KEY_0 = 0x30, // 0 key
64 | KEY_1 = 0x31, // 1 key
65 | KEY_2 = 0x32, // 2 key
66 | KEY_3 = 0x33, // 3 key
67 | KEY_4 = 0x34, // 4 key
68 | KEY_5 = 0x35, // 5 key
69 | KEY_6 = 0x36, // 6 key
70 | KEY_7 = 0x37, // 7 key
71 | KEY_8 = 0x38, // 8 key
72 | KEY_9 = 0x39, // 9 key
73 | // 0x3A-0x40, // Undefined
74 | KEY_A = 0x41, // A key
75 | KEY_B = 0x42, // B key
76 | KEY_C = 0x43, // C key
77 | KEY_D = 0x44, // D key
78 | KEY_E = 0x45, // E key
79 | KEY_F = 0x46, // F key
80 | KEY_G = 0x47, // G key
81 | KEY_H = 0x48, // H key
82 | KEY_I = 0x49, // I key
83 | KEY_J = 0x4A, // J key
84 | KEY_K = 0x4B, // K key
85 | KEY_L = 0x4C, // L key
86 | KEY_M = 0x4D, // M key
87 | KEY_N = 0x4E, // N key
88 | KEY_O = 0x4F, // O key
89 | KEY_P = 0x50, // P key
90 | KEY_Q = 0x51, // Q key
91 | KEY_R = 0x52, // R key
92 | KEY_S = 0x53, // S key
93 | KEY_T = 0x54, // T key
94 | KEY_U = 0x55, // U key
95 | KEY_V = 0x56, // V key
96 | KEY_W = 0x57, // W key
97 | KEY_X = 0x58, // X key
98 | KEY_Y = 0x59, // Y key
99 | KEY_Z = 0x5A, // Z key
100 | LWIN = 0x5B, // Left Windows key (Microsoft Natural keyboard)
101 | RWIN = 0x5C, // Right Windows key (Natural keyboard)
102 | APPS = 0x5D, // Applications key (Natural keyboard)
103 | // 0x5E, // Reserved
104 | SLEEP = 0x5F, // Computer Sleep key
105 | NUMPAD0 = 0x60, // Numeric keypad 0 key
106 | NUMPAD1 = 0x61, // Numeric keypad 1 key
107 | NUMPAD2 = 0x62, // Numeric keypad 2 key
108 | NUMPAD3 = 0x63, // Numeric keypad 3 key
109 | NUMPAD4 = 0x64, // Numeric keypad 4 key
110 | NUMPAD5 = 0x65, // Numeric keypad 5 key
111 | NUMPAD6 = 0x66, // Numeric keypad 6 key
112 | NUMPAD7 = 0x67, // Numeric keypad 7 key
113 | NUMPAD8 = 0x68, // Numeric keypad 8 key
114 | NUMPAD9 = 0x69, // Numeric keypad 9 key
115 | MULTIPLY = 0x6A, // Multiply key
116 | ADD = 0x6B, // Add key
117 | SEPARATOR = 0x6C, // Separator key
118 | SUBTRACT = 0x6D, // Subtract key
119 | DECIMAL = 0x6E, // Decimal key
120 | DIVIDE = 0x6F, // Divide key
121 | F1 = 0x70, // F1 key
122 | F2 = 0x71, // F2 key
123 | F3 = 0x72, // F3 key
124 | F4 = 0x73, // F4 key
125 | F5 = 0x74, // F5 key
126 | F6 = 0x75, // F6 key
127 | F7 = 0x76, // F7 key
128 | F8 = 0x77, // F8 key
129 | F9 = 0x78, // F9 key
130 | F10 = 0x79, // F10 key
131 | F11 = 0x7A, // F11 key
132 | F12 = 0x7B, // F12 key
133 | F13 = 0x7C, // F13 key
134 | F14 = 0x7D, // F14 key
135 | F15 = 0x7E, // F15 key
136 | F16 = 0x7F, // F16 key
137 | F17 = 0x80, // F17 key
138 | F18 = 0x81, // F18 key
139 | F19 = 0x82, // F19 key
140 | F20 = 0x83, // F20 key
141 | F21 = 0x84, // F21 key
142 | F22 = 0x85, // F22 key, (PPC only) Key used to lock device.
143 | F23 = 0x86, // F23 key
144 | F24 = 0x87, // F24 key
145 | // 0x88-0X8F, // Unassigned
146 | NUMLOCK = 0x90, // NUM LOCK key
147 | SCROLL = 0x91, // SCROLL LOCK key
148 | // 0x92-0x96, // OEM specific
149 | // 0x97-0x9F, // Unassigned
150 | LSHIFT = 0xA0, // Left SHIFT key
151 | RSHIFT = 0xA1, // Right SHIFT key
152 | LCONTROL = 0xA2, // Left CONTROL key
153 | RCONTROL = 0xA3, // Right CONTROL key
154 | LMENU = 0xA4, // Left MENU key
155 | RMENU = 0xA5, // Right MENU key
156 | BROWSER_BACK = 0xA6, // Windows 2000/XP: Browser Back key
157 | BROWSER_FORWARD = 0xA7, // Windows 2000/XP: Browser Forward key
158 | BROWSER_REFRESH = 0xA8, // Windows 2000/XP: Browser Refresh key
159 | BROWSER_STOP = 0xA9, // Windows 2000/XP: Browser Stop key
160 | BROWSER_SEARCH = 0xAA, // Windows 2000/XP: Browser Search key
161 | BROWSER_FAVORITES = 0xAB, // Windows 2000/XP: Browser Favorites key
162 | BROWSER_HOME = 0xAC, // Windows 2000/XP: Browser Start and Home key
163 | VOLUME_MUTE = 0xAD, // Windows 2000/XP: Volume Mute key
164 | VOLUME_DOWN = 0xAE, // Windows 2000/XP: Volume Down key
165 | VOLUME_UP = 0xAF, // Windows 2000/XP: Volume Up key
166 | MEDIA_NEXT_TRACK = 0xB0,// Windows 2000/XP: Next Track key
167 | MEDIA_PREV_TRACK = 0xB1,// Windows 2000/XP: Previous Track key
168 | MEDIA_STOP = 0xB2, // Windows 2000/XP: Stop Media key
169 | MEDIA_PLAY_PAUSE = 0xB3,// Windows 2000/XP: Play/Pause Media key
170 | LAUNCH_MAIL = 0xB4, // Windows 2000/XP: Start Mail key
171 | LAUNCH_MEDIA_SELECT = 0xB5, // Windows 2000/XP: Select Media key
172 | LAUNCH_APP1 = 0xB6, // Windows 2000/XP: Start Application 1 key
173 | LAUNCH_APP2 = 0xB7, // Windows 2000/XP: Start Application 2 key
174 | // 0xB8-0xB9, // Reserved
175 | OEM_1 = 0xBA, // Used for miscellaneous characters; it can vary by keyboard.
176 | // Windows 2000/XP: For the US standard keyboard, the ';:' key
177 | OEM_PLUS = 0xBB, // Windows 2000/XP: For any country/region, the '+' key
178 | OEM_COMMA = 0xBC, // Windows 2000/XP: For any country/region, the ',' key
179 | OEM_MINUS = 0xBD, // Windows 2000/XP: For any country/region, the '-' key
180 | OEM_PERIOD = 0xBE, // Windows 2000/XP: For any country/region, the '.' key
181 | OEM_2 = 0xBF, // Used for miscellaneous characters; it can vary by keyboard.
182 | // Windows 2000/XP: For the US standard keyboard, the '/?' key
183 | OEM_3 = 0xC0, // Used for miscellaneous characters; it can vary by keyboard.
184 | // Windows 2000/XP: For the US standard keyboard, the '`~' key
185 | // 0xC1-0xD7, // Reserved
186 | // 0xD8-0xDA, // Unassigned
187 | OEM_4 = 0xDB, // Used for miscellaneous characters; it can vary by keyboard.
188 | // Windows 2000/XP: For the US standard keyboard, the '[{' key
189 | OEM_5 = 0xDC, // Used for miscellaneous characters; it can vary by keyboard.
190 | // Windows 2000/XP: For the US standard keyboard, the '\|' key
191 | OEM_6 = 0xDD, // Used for miscellaneous characters; it can vary by keyboard.
192 | // Windows 2000/XP: For the US standard keyboard, the ']}' key
193 | OEM_7 = 0xDE, // Used for miscellaneous characters; it can vary by keyboard.
194 | // Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key
195 | OEM_8 = 0xDF, // Used for miscellaneous characters; it can vary by keyboard.
196 | // 0xE0, // Reserved
197 | // 0xE1, // OEM specific
198 | OEM_102 = 0xE2, // Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
199 | // 0xE3-E4, // OEM specific
200 | PROCESSKEY = 0xE5, // Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key
201 | // 0xE6, // OEM specific
202 | PACKET = 0xE7, // Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP
203 | // 0xE8, // Unassigned
204 | // 0xE9-F5, // OEM specific
205 | ATTN = 0xF6, // Attn key
206 | CRSEL = 0xF7, // CrSel key
207 | EXSEL = 0xF8, // ExSel key
208 | EREOF = 0xF9, // Erase EOF key
209 | PLAY = 0xFA, // Play key
210 | ZOOM = 0xFB, // Zoom key
211 | NONAME = 0xFC, // Reserved
212 | PA1 = 0xFD, // PA1 key
213 | OEM_CLEAR = 0xFE // Clear key
214 | }
215 |
216 | ///
217 | /// Internal callback processing function
218 | ///
219 | private delegate IntPtr KeyboardHookHandler(int nCode, IntPtr wParam, IntPtr lParam);
220 | private KeyboardHookHandler hookHandler;
221 |
222 | ///
223 | /// Function that will be called when defined events occur
224 | ///
225 | /// VKeys
226 | public delegate void KeyboardHookCallback(VKeys key);
227 |
228 | #region Events
229 | public event KeyboardHookCallback KeyDown;
230 | public event KeyboardHookCallback KeyUp;
231 | #endregion
232 |
233 | ///
234 | /// Hook ID
235 | ///
236 | private IntPtr hookID = IntPtr.Zero;
237 |
238 | ///
239 | /// Install low level keyboard hook
240 | ///
241 | public void Install() {
242 | hookHandler = HookFunc;
243 | hookID = SetHook(hookHandler);
244 | }
245 |
246 | ///
247 | /// Remove low level keyboard hook
248 | ///
249 | public void Uninstall() {
250 | UnhookWindowsHookEx(hookID);
251 | }
252 |
253 | ///
254 | /// Registers hook with Windows API
255 | ///
256 | /// Callback function
257 | /// Hook ID
258 | private IntPtr SetHook(KeyboardHookHandler proc) {
259 | using (ProcessModule module = Process.GetCurrentProcess().MainModule)
260 | return SetWindowsHookEx(13, proc, GetModuleHandle(module.ModuleName), 0);
261 | }
262 |
263 | ///
264 | /// Default hook call, which analyses pressed keys
265 | ///
266 | private IntPtr HookFunc(int nCode, IntPtr wParam, IntPtr lParam) {
267 | if (nCode >= 0) {
268 | int iwParam = wParam.ToInt32();
269 |
270 | if ((iwParam == WM_KEYDOWN || iwParam == WM_SYSKEYDOWN))
271 | if (KeyDown != null)
272 | KeyDown((VKeys)Marshal.ReadInt32(lParam));
273 | if ((iwParam == WM_KEYUP || iwParam == WM_SYSKEYUP))
274 | if (KeyUp != null)
275 | KeyUp((VKeys)Marshal.ReadInt32(lParam));
276 | }
277 |
278 | return CallNextHookEx(hookID, nCode, wParam, lParam);
279 | }
280 |
281 | ///
282 | /// Destructor. Unhook current hook
283 | ///
284 | ~KeyboardHook() {
285 | Uninstall();
286 | }
287 |
288 | ///
289 | /// Low-Level function declarations
290 | ///
291 | #region WinAPI
292 | private const int WM_KEYDOWN = 0x100;
293 | private const int WM_SYSKEYDOWN = 0x104;
294 | private const int WM_KEYUP = 0x101;
295 | private const int WM_SYSKEYUP = 0x105;
296 |
297 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
298 | private static extern IntPtr SetWindowsHookEx(int idHook, KeyboardHookHandler lpfn, IntPtr hMod, uint dwThreadId);
299 |
300 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
301 | [return: MarshalAs(UnmanagedType.Bool)]
302 | private static extern bool UnhookWindowsHookEx(IntPtr hhk);
303 |
304 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
305 | private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
306 |
307 | [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
308 | private static extern IntPtr GetModuleHandle(string lpModuleName);
309 | #endregion
310 | }
311 | }
--------------------------------------------------------------------------------