c# - 使用 SendMessage 从 Scintilla 控件中检索文本

标签 c# sendmessage scintilla

我正在尝试使用 C# 中的 SendMessage 在 Notepad++ 中检索文档文本。以下是我当前的代码。第一次调用 SendMessage 会正确返回文本的长度。对 SendMessage 的第二次调用不会将文本插入到 StringBuilder 变量文本中。为什么不呢?

    [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
    static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);

    [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Auto)]
    static extern int SendMessage(IntPtr hWnd, int msg, int wParam, StringBuilder lParam);


    var length = SendMessage(hWnd, 2183, 0,0);
    var text = new StringBuilder(length +1);
    SendMessage(hWnd, 2182, length + 1, text);

最佳答案

问题是您向 Scintilla 控件发送一条消息,该消息在 lParam 中具有您的 StringBuilder 缓冲区的地址,但 Notepad++ 中的 Scintilla 控件位于不同的地址空间中,因此它接收到的窗口消息中的地址可以不被写入。 WM_GETTEXTWM_SETTEXT 等标准消息的处理方式是为您执行必要的地址映射,但这不会发生在 Scintilla 控件使用的特殊消息中。有关更多信息,请查找编码。

不幸的是,对 WM_GETTEXTLENGTHWM_GETTEXT 的支持正在逐步退出 Scintilla 控件,文档建议使用特殊的 SCI_XXX 消息。 Notepad++ 已经无法与 WM_GETTEXT 一起使用,因此您需要使用 SCI_GETTEXTLENGTH (2183) 和 SCI_GETTEXT (2182),并自行进行编码。

警告:如果不对缓冲区地址进行特殊处理,从另一个应用程序发送 SCI_GETTEXT 消息实际上是危险的 - Notepad++ 会将数据复制到缓冲区,但由于该地址在其内部无效自己的地址空间,这会立即导致访问冲突,或者(更糟的是)它可能会悄悄地覆盖内部数据。


您可以使用 VirtualAllocEx() 和 ReadProcessMemory() 来使用具有可供 Notepad++ 使用的地址的缓冲区。我整理了一个适合我的快速 Delphi 程序,重要的代码是这样的:

procedure TForm1.Button1Click(Sender: TObject);
const
  VMFLAGS = PROCESS_VM_OPERATION or PROCESS_VM_READ or PROCESS_VM_WRITE;
var
  Wnd: HWND;
  Len: integer;
  ProcessId, BytesRead: Cardinal;
  ProcessHandle: THandle;
  MemPtr: PChar;
  s: string;
begin
  Wnd := $30488;
  Len := SendMessage(Wnd, 2183, 0, 0);
  if Len > 0 then begin
    GetWindowThreadProcessId(Wnd, @ProcessId);
    ProcessHandle := OpenProcess(VMFLAGS, FALSE, ProcessId);
    MemPtr := VirtualAllocEx(ProcessHandle, nil, Len + 1,
      MEM_RESERVE or MEM_COMMIT, PAGE_READWRITE);
    if MemPtr <> nil then try
      SendMessage(Wnd, 2182, Len + 1, integer(MemPtr));
      SetLength(s, Len + 1);
      ReadProcessMemory(ProcessHandle, MemPtr, @s[1], Len + 1, BytesRead);
      SetLength(s, BytesRead);
      Memo1.Lines.Text := s;
    finally
      VirtualFreeEx(ProcessId, MemPtr, Len + 1, MEM_RELEASE);
    end;
  end;
end;

这是使用 API 函数的 Ansi 版本的早期 Delphi 版本,您可能会使用 SendMessageW 和 WideChar 缓冲区,但总体思路应该很清楚。

关于c# - 使用 SendMessage 从 Scintilla 控件中检索文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/573814/

相关文章:

delphi - DScintilla 是否有语法突出显示的示例?

c# - 在 Scintilla.NET 中更改语法颜色

c# - Angular Controller 未被调用

c# - 如何用零填充二进制字符串?

c++ - SendMessage 与 PostMessage + WaitForSingleObject

c++ - 读取文件并将其添加到文本框 : string conversion issue

c# - 如何将字符串发送到其他应用程序,包括 Microsoft Word

c# - 获得对 C# 组件中鼠标点击的访问权限

c# - catch 语句中的附加 try 语句 - 代码味道?

c# - MS CRM 插件的一般错误