0

I am trying to copy the selected text in the active window using the win32 API SendMessage as following

[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, out int wParam, out int lParam);
int start,next;
SendMessage(activeWindowHandle, 0xB0, out start, out next);

This returns the starting and ending character position of the selected text. This works fine in notepad or any System.Windows.Forms.TextBox. But calling this for a System.Windows.Forms.RichTextBox returns one character less. anyone know why?? and how to work around this.

Anand
  • 4,182
  • 6
  • 42
  • 54
  • Can you give an example of what you expect it to return and what it actually returns? – Mattias S Dec 10 '09 at 10:55
  • well, now i've figured out what was happening, but not how to work around it. it was not getting one character less but actually in selecting from a RichTextBox it selects the '\n\r' character. But when i called the win32API to get the length of selected characters in the foreground window it did not count this as one char. so now i have "abc'\n\r'def" as 6 characters counted under selection but it returns only "abcde" instead of "abcdef" this works fine in notepad and simple text editors but not in richtextbox. so no way my code can know from where i am copying!! – Anand Dec 16 '09 at 14:23

1 Answers1

-1

SendMessage should actually be

public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);

wParam and lParam are in fact inputs, not outputs. Hence, you're sending garbage, and lucky to get something back.

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • Actually i was thinking there are two types of SendMessage. I found this solution on another forum and happened to copy it from there. Because this works fine with notepad or any simple text, but when using it in WORD or any tabbed window or "RichTextBox" this does not work at all. Could you please check out "http://stackoverflow.com/questions/1859061/how-can-i-simulate-ctrlc-in-c" and help me out. – Anand Dec 07 '09 at 10:25
  • No, SendMessage is a documented Win32 API, and the documentation leaves no doubt. See http://msdn.microsoft.com/en-us/library/ms644950(VS.85).aspx – MSalters Dec 07 '09 at 10:41
  • @MSalters: SendMessage is one of the most versatile API there is in Windows. The type of the wParam and lParam parameters depend entirely on what message you're passing, and they can be both input and output parameters. In this case, passing EM_GETSEL, it's entirely correct to make wParam and lParam out ints. http://msdn.microsoft.com/en-us/library/bb761598(VS.85).aspx The only change I'd do is to make the return type an IntPtr. – Mattias S Dec 10 '09 at 10:51