0

Here is my scenario: A user has two applications open. Let's say one application is Notepad with some text in it and the other one is my C# application.

A user now positions the mouse cursor somewhere inside the Notepad text and then clicks a button in my C# application. As a result, a text string from my application gets pasted in Notepad where the cursor was positioned.

My question is: what would a general approach be to accomplish the above, and possibly what classes etc. are recommended?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 5
    I would highly discourage you from doing this. Instead, simply have the button in your application copy the information to the clipboard (a simple search will show you how to do this). Let the user paste that text into whatever application they want, wherever they want, explicitly. Trying to do that for them is going to be dangerous, error prone, confusing to the user, difficult, and unreliable. – Servy May 29 '14 at 19:38
  • Thanks John, noted everything. Fyi, I agree that in general this is not how one would do it, but a wider scope of my application actually requires this action be done as I described. – user3688935 May 29 '14 at 19:50
  • This might be really difficult since when the user clicks the button in your C# application, notepad would lose focus and I don't know if you can reliably get cursor text position from there via interop. – David Zech May 29 '14 at 19:51
  • This sounds like a prime use case for a tiny and trivial autohotkey script. Are you 100% _required_ to solve this program in C#? – clarkitect May 29 '14 at 20:01
  • I checked out autohotkey and it looks great, but I do need to have the functionality built into my C# application. I'll probably start looking at autohokey only if I hit a brick wall using interop. – user3688935 May 30 '14 at 21:42

1 Answers1

1

I would look into using interop calls to accomplish this. Look at specifically GetWindow() and SendMessage with the WM commands (http://msdn.microsoft.com/en-us/library/windows/desktop/ms644927(v=vs.85).aspx#system_defined) and GetDesktop().

GetDesktop will allow you to obtain all of the top level child windows of the desktop (all top level windows are children of the Desktop window).

You should then be able to use GetWindow to obtain the window handle you are looking for and then SendMessage to set the text into the textbox.

Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
  • Thanks Mike, I thought the solution lay with interop and will dig into that now. I presume I should be able to get the Window I'm looking for easily and send it a message, but in this particular instance, I need to paste a text right on the position where the cursor was in Notepad, before my button is clicked. – user3688935 May 29 '14 at 19:48
  • I think you can get the cursor position using winapi function GetCaretPos http://msdn.microsoft.com/en-us/library/ms648402%28v=vs.85%29.aspx – Mike Cheel May 29 '14 at 19:49