将文本拖放到SynEdit控件中

时间:2012-06-19 09:54:33

标签: delphi drag-and-drop synedit

我在表单上有一个 TSynEdit 控件,我想从 TVirtualStringTree 拖放聚焦节点文本。我希望它的行为方式与在 TSynEdit 控件中拖放突出显示的文本时的行为方式相同:

  • 当您拖动 TSynEdit 时,插入符号应标记当前的放置位置。
  • 删除文本时,应替换当前突出显示的任何文本。
  • 放置位置应正确处理标签。

我查看了 TSynEdit DragOver 事件中的代码,但它使用了几个变量和过程,我们无法在后代类中访问这些变量和过程的私有

我已经检查了所有 TSynEdit 演示,找不到满足我需求的演示。

有人成功地成功完成了这项工作吗?

2 个答案:

答案 0 :(得分:2)

AZ01的回答并没有完全符合我的要求,但确实指出了我正确的方向。这是我最终使用的代码:

procedure TfrmTemplateEdit.memTemplateDragDrop(Sender, Source: TObject; X,
  Y: Integer);
var
  InsertText: String;
  ASynEdit: TSynEdit;
  OldSelStart, DropIndex: Integer;
  LCoord: TBufferCoord;
begin
  // Set the Insert Text
  InsertText := 'The text to insert';

  // Set the SynEdit memo
  ASynEdit := TSynEdit(Sender);

  // Get the position on the mouse
  ASynEdit.GetPositionOfMouse(LCoord);

  // Find the index of the mouse position
  DropIndex := ASynEdit.RowColToCharIndex(LCoord);

  // Delete any selected text
  If (ASynEdit.SelAvail) and
     (DropIndex >= ASynEdit.SelStart) and
     (DropIndex <= ASynEdit.SelEnd) then
  begin
    // Store the old selection start
    OldSelStart := ASynEdit.SelStart;

    // Delete the text
    ASynEdit.ExecuteCommand(ecDeleteChar, #0, Nil);

    // Move the caret
    ASynEdit.SelStart := OldSelStart;
  end
  else
  begin
    // Position the caret at the mouse location
    ASynEdit.CaretXY := LCoord;
  end;

  // Insert the text into the memo
  ASynEdit.ExecuteCommand(ecImeStr, #0, PWideChar(InsertText));

  // Set the selection start and end points to selected the dropped text
  ASynEdit.SelStart := ASynEdit.SelStart - length(InsertText);
  ASynEdit.SelEnd := ASynEdit.SelStart + length(InsertText);

  // Set the focus to the SynEdit
  ASynEdit.SetFocus;
end;

代码似乎与选择,制表符和撤消功能正常。

答案 1 :(得分:1)

我认为您可以通过为编辑器分配两个事件来实现目标:DragOver / DragDrop。

1 /您在 DragOver事件中测试有效性,您还可以通过调用 GetPositionOfMouse

来移动插入符号
Procedure TForm1.EditorDragOver(Sender,Source: TObject;X,Y: Integer; State: TDragState; Var Accept: Boolean);
Var
  LCoord: TBufferCoord;
  LMemo: TSynMemo;
Begin
  LMemo := TSynMemo(Sender);
  // In your case you would rather test something with your tree...
  Accept := Clipboard.AsText <> '';
  // "As you drag over the TSynEdit, the caret should mark the current drop position": OK
  If LMemo.GetPositionOfMouse(LCoord) Then
    LMemo.CaretXY := LCoord;
End;

2 /您使用 DragDrop事件中的编辑器命令清除选择并插入字符

Procedure TForm1.EditorDragDrop(Sender, Source: TObject; X,Y: Integer);
Var
  LMemo: TSynMemo;
Begin
  LMemo := TSynMemo(Sender);
  // "When the text is dropped, it should replace any text that is currently highlighted." : OK
  If LMemo.SelAvail Then
    LMemo.ExecuteCommand( ecDeleteChar , #0, Nil );
  // Paste, same comment as previously, here it's just an example...
  LMemo.ExecuteCommand( ecPaste, #0, Nil );
End;

根据您的具体情况,这需要进行一些调整。