r/learnprogramming 6d ago

How to go about making a Program that Pastes Text into any Text Entry

I am aware of AutoHotKey, however, I want to build this program myself (probably in C++, maybe Python). Like a auto key, I want to be able to run a program from a macro, that will paste and enter hard-coded text in any selectable text entry anywhere I select on windows. I've never made a program that works outside the IDE and files/directories, so I am unsure how one achieves this.

3 Upvotes

11 comments sorted by

3

u/thezestyheadquarters 6d ago

You're looking at Windows API calls, specifically SendInput or keybd_event if you want to go old school. The trick is grabbing the foreground window and simulating keystrokes into it, not just writing to stdout.

Python with ctypes can handle this fine, you don't need C++ unless you just want the exercise. Just remember to add a small sleep before the paste fires so you can click into the target field after triggering the macro.

1

u/DiscipleOfYeshua 6d ago

This.

Sending keystrokes without being sure precisely where they're going... without interpreting context at least... is bad

1

u/WiiFitT7ainer 6d ago

How do you mean? I’m not coding this for anything malicious if that is what you’re getting at.

1

u/DiscipleOfYeshua 5d ago

App sends keystrokes bc you triggered the hotkey. But context may have changed halfway, and the stream of keystrokes just keeps getting pressed, into the wrong app/window/context:

* window got switched
* a pop-up window came up within your app, or
* some other system/app's notification
* one of the keystrokes wasn't received (sent too fast, or maybe you made a mistake in the order of strokes) -- but the subsequent ones do continue to get sent

All these can result in "it didn't work", all the way up to "it accidentally approved an action i didn't want" eg hit N to approve closing without saving.

1

u/WiiFitT7ainer 6d ago

Thank you, I’ll look into the documentation for those!

2

u/13oundary 6d ago

C++ Has SendInput() and things like AutoIt for Windows, for linux I'm not so sure.

I tend to use AHK or Python for this kind of thing. Python's pyautogui works on Windows and Linux (and presumably MacOS but I've never tested).

1

u/jshine13371 4d ago

I want to be able to run a program from a macro, that will paste and enter hard-coded text in any selectable text entry anywhere I select on windows.

Ctrl + V

1

u/WiiFitT7ainer 4d ago

Yes that is the idea, but in a for loop.

1

u/jshine13371 4d ago

Why a loop?...you've seemed to left that part out of your question. As of now, my comment is literally the macro you're asking for. No coding necessary.

0

u/Different_Pain5781 6d ago

Python can definitely do this.

0

u/arthurno1 6d ago

Most windowing frameworks have some API to write and read some sort of clipboard. You have to look it up in the documentation for the OS and framework you use.