6

I have windows forms application with multiple forms and controls in them. I want if user has selected some text in any control of any form of my application and click on cut/copy/paste button on toolbar operation get performed accordingly.

i m using C#.net's sendkeys.send("^c") on click of copy button but it doesn't work...

OR any 1 can tell if is there any way to get selected text (despite of knowing, which form/control of my application).

Thanks in advance...

default locale
  • 13,035
  • 13
  • 56
  • 62
Muhammad Adnan
  • 1,375
  • 6
  • 19
  • 40

3 Answers3

5

have you used clipboard to copy and paste you data if not than use clipboard for this

check this article for more about clipboard: http://www.geekpedia.com/tutorial188_Clipboard-Copy-and-Paste-with-Csharp.html

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • 1
    Thanks for your reply. I checked the link. in that case programmer knows which textbox is selected. i want generic solution. suppose i have data grid with thousands of rows and columns. now i don't know which cells text user selected. i have many forms to deal with. as user can open multiple forms at the same time. so i dont wanna implement such technique for each control and form. just looking for generic way. – Muhammad Adnan Jun 09 '10 at 12:27
  • 1
    than check this may help you : http://www.voidspace.org.uk/ironpython/winforms/part8.shtml – Pranay Rana Jun 09 '10 at 12:42
2

I use this in the method handling the copy event:

if (this.ActiveControl is TextBox)
{
      Clipboard.SetDataObject(((TextBox)this.ActiveControl).SelectedText, true);
}
if (this.ActiveControl is RichTextBox)
{
      Clipboard.SetDataObject(((RichTextBox)this.ActiveControl).SelectedText, true);
}
if (this.ActiveControl is ComboBox)
{
       Clipboard.SetDataObject(((ComboBox)this.ActiveControl).SelectedText, true);
}

For paste, something like this:

nCursorPosition = ((RichTextBox)this.ActiveControl).SelectionStart;
this.ActiveControl.Text = this.ActiveControl.Text.Insert(nCursorPosition, Clipboard.GetText());
Rox
  • 1,985
  • 12
  • 19
  • 1
    i have mdi application with multiple forms each form can have multiple textboxes when user select some text in any form and press copy button in main menu of the application i want that selected text get copied – Muhammad Adnan Jun 09 '10 at 12:56
1

To your second question:

You can use this solution What is the preferred way to find focused control in WinForms app? to find the currently focused control.

Then check, what type it is to read the selection (i.e. if it is TextBox use SelectedText-Propery http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.selectedtext.aspx)

Community
  • 1
  • 1
Hinek
  • 9,519
  • 12
  • 52
  • 74
  • 1
    it doesn't work for me. as i have MDI application. by getting active control i get clicked button of toolbar rather that textbox where i selected text of another form (mdi child) – Muhammad Adnan Jun 09 '10 at 12:57