简体   繁体   中英

WPF c# copy and paste to clipboard

I want to make a WPF program which converts unit (numbers from other applications). I made my program can run at system tray and I can set global hotkey too. But it's my first time making a WPF program so I'm having some problems.

This function is called when user presses global hotkey. To calculate, I need to copy/paste selected text from other application. I would appreciate it if you help me. (The code might be a little messy)

  • My user wants automatically convert his selected text.
  • He is using my application like this now: 1. Select text 2. Press Ctrl+C 3. Press Ctrl+D(Global Hotkey) 4. Press Ctrl+V.
  • What he wants is: 1. Select text 2. Press Ctrl+D(Global Hotkey) and it's done.

     void ClipboardCalc() { string resultStr = string.Empty; string temp = string.Empty; string digit = string.Empty; double result = 0; temp = Clipboard.GetText(); // Need to copy "selected text from other application" to clipboard here. resultStr = Clipboard.GetText(); resultStr = string.Join(string.Empty, Regex.Match(resultStr, @"\\d+(\\.\\d+)?")); try { result = Convert.ToDouble(resultStr); } catch (Exception ee) { } if (reverse_mode == false) result *= 3.30579; else result /= 3.30579; digit = "F" + textBox2.Text; if (result == (int)result) resultStr = result.ToString(); else resultStr = result.ToString(digit); resultStr = string.Format("{0:0.##########}", Convert.ToDouble(resultStr)); if (print_measure != false) { if (reverse_mode != false) resultStr += "평"; else resultStr += "m²"; } Clipboard.SetText(resultStr); // Then paste clipboard text here. //Clipboard.SetText(temp); }

This is a bodge sort of answer, but it seems like a bodge sort of program, so I'll put it out there anyway.

If you've managed to set up a "global hotkey", then I'm assuming you've already gotten into p/invoke territory. So I might as well introduce you to SendInput . This native method lets an application "synthesize keystrokes, mouse motions, and button clicks to the currently active window". You can use it to send Ctrl+C to the active window.

Again, a bodged solution with a lot of assumptions, but it will probably work in most cases.

Note that you'll have to send key down and key up inputs individually (ie "Ctrl down", "C down", "C up", "Ctrl up", in that order).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM