locked
How can i get selected text from active window ? RRS feed

  • Question

  • Hi ....

    How can i get any selected text from active window by copy it to  clipboard ??

     

    i tried to use this code but (  SendKeys.SendWait("^c") ) just send key to active application ,, and my application maybe  minimized.

     

     

     private void Form1_Load(object sender, EventArgs e)

            {

                timer1.Interval = 1000; //Don't make it too short, because it may slow down the computer.

                timer1.Tick += new EventHandler(timer1_Tick);

                timer1.Start();

            }

     

     

     

    private void timer1_Tick(object sender, EventArgs e)

            {

                    SendKeys.SendWait("^c");         //Send a ctrl+c to the topmost application

     

                    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))

                    {

                          richTextBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();

                    }

     

     

    Tuesday, November 9, 2010 8:34 PM

Answers

  • What about this one?

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    namespace WindowsFormsApplication1
    {
      public partial class Form1 : Form
      {
        [DllImport("user32.dll", SetLastError = true)]
        private static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);
        private const uint VK_CONTROL = 0x11;
        private const uint VK_C = 0x43;
        private const uint INPUT_KEYBOARD = 1;
        private const uint KEYEVENTF_KEYUP = 0x2;
    
        public struct KEYBDINPUT
        {
          public ushort wVk;
          public ushort wScan;
          public uint dwFlags;
          public long time;
        };
    
        [StructLayout(LayoutKind.Explicit, Size = 28)]
        public struct INPUT
        {
          [FieldOffset(0)]
          public uint type;
          [FieldOffset(4)]
          public KEYBDINPUT ki;
        };
    
        private void sendctrlc()
        {
          uint intReturn;
          INPUT structInput;
          structInput = new INPUT();
          structInput.type = INPUT_KEYBOARD;
          structInput.ki.wScan = 0;
          structInput.ki.time = 0;
          structInput.ki.dwFlags = 0;
          structInput.ki.wVk = (ushort)VK_CONTROL;
          intReturn = SendInput(1, ref structInput, Marshal.SizeOf(new INPUT()));
          structInput.ki.wVk = (ushort)VK_C;
          intReturn = SendInput(1, ref structInput, Marshal.SizeOf(new INPUT()));
          structInput.ki.dwFlags = KEYEVENTF_KEYUP;
          intReturn = SendInput(1, ref structInput, Marshal.SizeOf(typeof(INPUT)));
          structInput.ki.wVk = (ushort)VK_CONTROL;
          intReturn = SendInput(1, ref structInput, Marshal.SizeOf(new INPUT()));
        }
    
        public Form1()
        {
          InitializeComponent();
          this.Resize += new EventHandler(Form1_Resize);
          timer1.Tick += new EventHandler(timer1_Tick);
        }
    
        private void Form1_Resize(object sender, EventArgs e)
        {
          if (WindowState == FormWindowState.Minimized)
          {
            timer1.Start();
          }
          else
          {
            timer1.Stop();
          }
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
          timer1.Interval = 1000;
        }
    
        private void timer1_Tick(object sender, EventArgs e)
        {
          sendctrlc();
          if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
          {
            richTextBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
          }
        }
      }
    }
    
    


    HrBill32
    • Marked as answer by Zizo0o Sunday, November 14, 2010 11:31 PM
    Sunday, November 14, 2010 5:32 AM

All replies

  • no one can help me ???
    Wednesday, November 10, 2010 10:03 AM
  • Hi Zizo0o,

     

    I tested your code. It works really great. When I minimize the app and click text in another app, I wait more than 1 second to let it copied into Clipboard. The RichTextBox in minimized app filled with the selected text. Do I misunderstand your issue?

     

    Sincerely,

    Kira Qian
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework!
    Thursday, November 11, 2010 8:34 AM
  • HI Kira Qian ...

    The code is work really great . but if my app window is not active ( minimized ) ... my application send key ("^c") continually to clip Board .

    Therefore, the program appears sound annoying ( sound look like  > msg box sound )  .

    after that i need to close my app to cancel this sound.

    Thursday, November 11, 2010 9:44 PM
  • HI Kira Qian ... The code is work really great . but if my app window is not active ( minimized ) ... my application send key ("^c") continually to clip Board . Therefore, the program appears sound annoying ( sound look like > msg box sound ) . after that i need to close my app to cancel this sound.
    Thursday, November 11, 2010 9:45 PM
  • HI Kira Qian ... The code is work really great . but if my app window is not active ( minimized ) ... my application send key ("^c") continually to clip Board . Therefore, the program appears sound annoying ( sound look like > msg box sound ) . after that i need to close my app to cancel this sound.


    Hi Zizo0o,

    Do you mean that when your application is not active you do not want the Ctrl+C keystroke to be sended? Please explain a bit more what are you trying to achieve. When exactly you want to close your application?


    Bill


    HrBill32
    Friday, November 12, 2010 1:56 AM
  • You can handle the Resize event and check the WindowState. If the WindowState is Minimized, set the Enabled property of Timer to false. Otherwise set it to true.

     

    Sincerely,

    Kira Qian
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework!
    Friday, November 12, 2010 2:56 AM
  • can u test this code ...  when u minimize the wind of the application > click on any other window and see what happens ??

    private void Form1_Resize(object sender, EventArgs e)

            {

                if (WindowState == FormWindowState.Minimized)

                {

                    timer1.Interval = 1000;

                    timer1.Tick += new EventHandler(timer1_Tick);

                    timer1.Start();

                }

            }


    ==//////////////////////////////////////////////////

     private void timer1_Tick(object sender, EventArgs e)
            {

                try
                {
                    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
                    {

                        SendKeys.SendWait("^c");
                        
                        richTextBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
                       
                    }
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.Message);
                }
            }

    Friday, November 12, 2010 4:11 PM
  • can u test this code ...  when u minimize the wind of the application > click on any other window and see what happens ??

     

    private void Form1_Resize(object sender, EventArgs e)

            {

                if (WindowState == FormWindowState.Minimized)

                {

                    timer1.Interval = 1000;

                    timer1.Tick += new EventHandler(timer1_Tick);

                    timer1.Start();

                }

            }


    ==//////////////////////////////////////////////////

     private void timer1_Tick(object sender, EventArgs e)
            {

                try
                {
                    if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
                    {

                        SendKeys.SendWait("^c");
                        
                        richTextBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
                       
                    }
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.Message);
                }
            }

     


    Hello Zizo0o,

    I can see some problems on your code.

    The SendKeys.SendWait("^c"); should be before the if statement because if you start your application with no text to the clipboard it will do nothing. When you minimize your window it starts the timer. When you restore it again don't you want to stop it?

    Create a new project and test this code:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication1
    {
      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
          this.Resize+=new EventHandler(Form1_Resize);
          timer1.Tick += new EventHandler(timer1_Tick);
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
          timer1.Interval = 1000;
        }
    
        private void Form1_Resize(object sender, EventArgs e)
        {
          if (WindowState == FormWindowState.Minimized)
          {
            timer1.Start();
          }
          else
          {
            timer1.Stop();
          }
        }
    
        private void timer1_Tick(object sender, EventArgs e)
        {
          SendKeys.SendWait("^c");
          if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
          {
            richTextBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
          }
        }
      }
    }
    
    

    This code will work as follows:

    When you minimize your window it will send the Ctrl+C keystroke every 1 second. If you have text selected then the richTextBox1 will equal with that text (it will not add this text it will just equal with it).

    When you go to your window again the previous operation will stop.

    Warning: Consider that your window has windowstate normal, if you click to another window your window is NOT being resized. Your window loses its focus but it is not being resized. If you click to minimize it then it is resized.

    If you explain more I may be able to help you more. Just say the way you want your application to work.

     

    Bill


    HrBill32
    Saturday, November 13, 2010 5:15 AM
  • Thanks HRBill32 ...

    i tried your code it's work perfectly but the application is " hung".

    ???????????????????

    Saturday, November 13, 2010 11:05 PM
  • Thanks HRBill32 ...

    i tried your code it's work perfectly but the application is " hung".

    ???????????????????

    You mean it is not responding? It works OK for me. However, if it is not responding for you try using SendKeys.Send instead of SendKeys.SendWait.


    HrBill32
    • Edited by HrBill32 Saturday, November 13, 2010 11:55 PM
    Saturday, November 13, 2010 11:36 PM
  • Yes it is not responding?
    Saturday, November 13, 2010 11:54 PM
  • Yes it is not responding?


    Even if you use SendKeys.Send?


    HrBill32
    Saturday, November 13, 2010 11:59 PM
  • Yes .

    i don't change any thing in the code .

    the application and the computer is not responding ????

    Sunday, November 14, 2010 12:05 AM
  • If you completely remove the line for sending the Ctrl+C keystroke, will it crash again? Give a try so that to find if this line makes the application to crash. If it will crash again then try changing another part of the code in order to find what crashes your application. I cannot find it because for me it works without crash, thus you must find it. When you find it I may be able to give you another method for that part.


    HrBill32
    Sunday, November 14, 2010 1:25 AM
  • i tried to use SendKeys.Send()  the same thing is happened (application crash)

    but when i delete the line for sending the Ctrl+C keystroke the application is working will ( no crash)

    Sunday, November 14, 2010 1:32 AM
  • Try this code:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    namespace WindowsFormsApplication1
    {
      public partial class Form1 : Form
      {
        [DllImport("user32.dll")]
        private static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
        private const byte VK_CONTROL = 0x11;
        private const byte VK_C = 0x43;
        private const uint KEYEVENTF_KEYUP = 0x2;
    
        public Form1()
        {
          InitializeComponent();
          this.Resize += new EventHandler(Form1_Resize);
          timer1.Tick += new EventHandler(timer1_Tick);
        }
    
        private void Form1_Resize(object sender, EventArgs e)
        {
          if (WindowState == FormWindowState.Minimized)
          {
            timer1.Start();
          }
          else
          {
            timer1.Stop();
          }
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
          timer1.Interval = 1000;
        }
    
        private void timer1_Tick(object sender, EventArgs e)
        {
          sendctrlc();
          if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
          {
            richTextBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
          }
        }
    
        private void sendctrlc()
        {
          keybd_event(VK_CONTROL, 0, 0, UIntPtr.Zero);
          keybd_event(VK_C, 0, 0, UIntPtr.Zero);
          keybd_event(VK_C, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
          keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, UIntPtr.Zero);
        }
      }
    }
    
    


    HrBill32
    Sunday, November 14, 2010 3:09 AM
  • Hi HrBill32 ...

    Thanks for your interest

    the code is working will, but it cause some problems with other windows ... when application is run for a long time it's make other windows not responding. i saw some applications uses ctrl+c  but without any problems.

    Sunday, November 14, 2010 3:32 AM
  • What about this one?

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    namespace WindowsFormsApplication1
    {
      public partial class Form1 : Form
      {
        [DllImport("user32.dll", SetLastError = true)]
        private static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);
        private const uint VK_CONTROL = 0x11;
        private const uint VK_C = 0x43;
        private const uint INPUT_KEYBOARD = 1;
        private const uint KEYEVENTF_KEYUP = 0x2;
    
        public struct KEYBDINPUT
        {
          public ushort wVk;
          public ushort wScan;
          public uint dwFlags;
          public long time;
        };
    
        [StructLayout(LayoutKind.Explicit, Size = 28)]
        public struct INPUT
        {
          [FieldOffset(0)]
          public uint type;
          [FieldOffset(4)]
          public KEYBDINPUT ki;
        };
    
        private void sendctrlc()
        {
          uint intReturn;
          INPUT structInput;
          structInput = new INPUT();
          structInput.type = INPUT_KEYBOARD;
          structInput.ki.wScan = 0;
          structInput.ki.time = 0;
          structInput.ki.dwFlags = 0;
          structInput.ki.wVk = (ushort)VK_CONTROL;
          intReturn = SendInput(1, ref structInput, Marshal.SizeOf(new INPUT()));
          structInput.ki.wVk = (ushort)VK_C;
          intReturn = SendInput(1, ref structInput, Marshal.SizeOf(new INPUT()));
          structInput.ki.dwFlags = KEYEVENTF_KEYUP;
          intReturn = SendInput(1, ref structInput, Marshal.SizeOf(typeof(INPUT)));
          structInput.ki.wVk = (ushort)VK_CONTROL;
          intReturn = SendInput(1, ref structInput, Marshal.SizeOf(new INPUT()));
        }
    
        public Form1()
        {
          InitializeComponent();
          this.Resize += new EventHandler(Form1_Resize);
          timer1.Tick += new EventHandler(timer1_Tick);
        }
    
        private void Form1_Resize(object sender, EventArgs e)
        {
          if (WindowState == FormWindowState.Minimized)
          {
            timer1.Start();
          }
          else
          {
            timer1.Stop();
          }
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
          timer1.Interval = 1000;
        }
    
        private void timer1_Tick(object sender, EventArgs e)
        {
          sendctrlc();
          if (Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
          {
            richTextBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
          }
        }
      }
    }
    
    


    HrBill32
    • Marked as answer by Zizo0o Sunday, November 14, 2010 11:31 PM
    Sunday, November 14, 2010 5:32 AM
  • it works will ,, but when i changed :

    richTextBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
    To >>>>>
    MessageBox.show(Clipboard.GetDataObject().GetData(DataFormats.Text).ToString());
    there are an infinite number of "messageBox" .

    Sunday, November 14, 2010 3:38 PM
  • it works will ,, but when i changed :

     

    richTextBox1.Text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
    To >>>>>
    MessageBox.show(Clipboard.GetDataObject().GetData(DataFormats.Text).ToString());
    there are an infinite number of "messageBox" .

     

    Yes, this is an issue using MessageBox.Show (generaly a dialog box) in a Timer.Tick event. Read here . This issue can be solved but using MessageBox.Show in timer1.Tick event is bad idea in this case. You will need to solve many other problems. I suggest that you should use a richtextbox as before. You could add the clipboard text to the richTextBox1 text (every second) instead of making richTextBox1 text equal with it. You could also use a string (for example "---Add---"), every time clipboard texts are being added, to separate them when you go back to your window. I hope my suggestions can help you.


    HrBill32
    Sunday, November 14, 2010 11:28 PM
  • yes HrBill32 you're right.
    Sunday, November 14, 2010 11:33 PM