Created
March 2, 2018 17:51
-
-
Save judge2020/35a82cedc017e2a5c3504e2ab6a9ab59 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Runtime.InteropServices; | |
| using System.Text; | |
| using System.Windows.Forms; | |
| namespace SendKeysToAnyApplication | |
| { | |
| class Program | |
| { | |
| delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); | |
| [DllImport("user32.dll")] | |
| static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, uint lParam); | |
| [DllImport("user32.dll")] | |
| static extern IntPtr FindWindow(string lpClassName, string lpWindowName); | |
| [DllImport("user32.dll")] | |
| static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam); | |
| [DllImport("user32.dll")] | |
| static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); | |
| const uint WM_CHAR = 0x102; | |
| const uint WM_PASTE = 0x0302; | |
| static IntPtr m_hWndEdit = IntPtr.Zero; | |
| [STAThread] | |
| static void Main(string[] args) | |
| { | |
| // for a test we use the notepad window | |
| // ... so lets have a look if we find an opened notepad window (better you open one first...) | |
| IntPtr hWnd = FindWindow("Notepad", null); | |
| // But! we can not send text to the main-window, we have to find the subwindow where the text is entered | |
| // So lets enumerate all child windows: | |
| IntPtr hWndEdit = IntPtr.Zero; | |
| EnumChildWindows(hWnd, EnumChildWindowsCallback, hWndEdit); | |
| if (m_hWndEdit != null) // edit window found? | |
| { | |
| // Now you could use different messages to send text (WM_CHAR, WM_KEYDOWN, ...) | |
| // I decided to use the clipboard: | |
| // Copy some text to the clipboard | |
| Clipboard.SetText("this is magic!"); | |
| // ... and just paste it to the target window | |
| SendMessage(m_hWndEdit, WM_PASTE, 0, 0); | |
| } | |
| } | |
| static bool EnumChildWindowsCallback(IntPtr hWnd, IntPtr lParam) | |
| { | |
| // Search for notepads edit window - if we find it "false" is returned (means stop enumerating windows) | |
| StringBuilder sb = new StringBuilder(); | |
| GetClassName(hWnd, sb, 256); | |
| if (!sb.ToString().Contains("Edit")) | |
| { | |
| return true; | |
| } | |
| m_hWndEdit = hWnd; // Store the handle to notepads edit window (this is the window we want to send the messages to) | |
| return false; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment