Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste text using windows paste command to other application in c#?

Tags:

c#

How calling interop to paste text using windows pastse command to other application in c#?

calling interop?

i mean how to programing c# same right click to past text

like image 979
zXXXz Avatar asked Dec 21 '22 23:12

zXXXz


2 Answers

This can be a bit tricky in some scenarios, but it's actually quite simple and easy to do. Below is an example on how to get some text using a text box, (called uxData in this case), open Notepad from code, and to paste the text from the clipboard to Notepad.

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
    }

    [DllImport("user32.dll", SetLastError = true)]
    private static extern bool BringWindowToTop(IntPtr hWnd);

    private void OnClicked_PasteToNotepad(object sender, EventArgs e) {

        // Let's start Notepad
        Process process = new Process();
        process.StartInfo.FileName = "C:\\Windows\\Notepad.exe";
        process.Start();

        // Give the process some time to startup
        Thread.Sleep(10000);

        // Copy the text in the datafield to Clipboard
        Clipboard.SetText(uxData.Text, TextDataFormat.Text);

        // Get the Notepad Handle
        IntPtr hWnd = process.Handle;

        // Activate the Notepad Window
        BringWindowToTop(hWnd);

        // Use SendKeys to Paste
        SendKeys.Send("^V");
    }
}

Now, say you want to paste into a specific field. This is where you will need to use FindWindow and FindWindowEx, to get the handle of the field you want to paste into. Here are the steps once you have copied your data to the clipboard.

  1. Get the process handle
  2. Bring the process into focus (Activate it)
  3. Find the handle of the field you wish to paste into
  4. Set focus to that field
  5. Use SendKeys to paste from clipboard
like image 193
David Anderson Avatar answered May 12 '23 22:05

David Anderson


You can use Clipboard class in System.Windows.Forms to inspect types of data the clipboard contains and fetch this data if needed. Clipboard in Windows holds the data "to be pasted", which can be a bitmap, text, HTML, RTF etc.

It's not quite clear what you mean by "paste". Is that "paste" supposed to happen when a button is clicked, a key is pressed or something else? Text box controls (richbox, combobox etc.) typically respond to Ctrl-V (standard Paste keystroke) and will auto-insert the text in the appropriate format (plain, RTF) from the clipboard, so you don't have to do anything manually.

In all other cases you need to decide what data you're interested in and extract it from the clipboard using appropriate methods.

like image 23
liggett78 Avatar answered May 12 '23 23:05

liggett78