希望你已经得到了答案。
我有自己的解决方案。
所以,我的要求:
我有一个自定义窗格,其中包含一个列表框,每个项目都是一个普通字符串。当我将列表框中的项目拖到文档中的特定位置时,我想在该位置插入一个合并字段。合并字段的名称是项目的文本。
一开始很简单,然后我遇到了一个问题,就像你在问题中描述的那样。
关于代码
所以,有一个列表框,你需要处理mouseDown和mouseMove,不用担心mouseUp。
在 mouseDown 处理程序中,我记录了边界,如果鼠标移出该边界,将开始拖动。
然后,在 listBox_MouseMoveHandler 中,我检查鼠标的位置以开始拖放。对于DoDragDrop 方法,我必须使用DragDropEffects.Copy。
DoDragDrop((sender as ListControl).SelectedValue, DragDropEffects.Copy);
使用该选项,SelectedValue 会被插入到 drop 位置,插入后也会被选中。
然后,我只是检查选择是否不为空,并将所选文本替换为合并字段。当然,我折叠了DoDragDrop之前的选择。这就是全部技巧。
private int _selectedItemIndex;
private Rectangle dragBoxFromMouseDown;
private void CustomizationForListBox(ListBox listBox)
{
listBox.ItemHeight = 25;
listBox.DrawMode = DrawMode.OwnerDrawFixed;
listBox.DrawItem += ListBox_DrawItem;
listBox.MouseDoubleClick += listBox_MouseDoubleClick;
listBox.MouseMove += listBox_MouseMoveHandler;
listBox.MouseUp += listBox_MouseUp;
listBox.MouseDown += (sender, e) =>
{
// Handle drag/drop
if (e.Button == MouseButtons.Left)
{
_selectedItemIndex = listBox.IndexFromPoint(e.Location);
// Remember the point where the mouse down occurred. The DragSize indicates
// the size that the mouse can move before a drag event should be started.
Size dragSize = SystemInformation.DragSize;
// Create a rectangle using the DragSize, with the mouse position being
// at the center of the rectangle.
dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2),
e.Y - (dragSize.Height / 2)), dragSize);
}
};
}
private void listBox_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// Reset the drag rectangle when the mouse button is raised.
dragBoxFromMouseDown = Rectangle.Empty;
}
}
private void listBox_MouseMoveHandler(object sender, MouseEventArgs e)
{
// Handle drag and drop
// To check if the Mouse left button is clicked
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
// If the mouse moves outside the rectangle, start the drag.
if (dragBoxFromMouseDown != Rectangle.Empty &&
!dragBoxFromMouseDown.Contains(e.X, e.Y))
{
// Collapse current selection, now we know nothing is selected
Globals.ThisAddIn.Application.Selection.Collapse(WdCollapseDirection.wdCollapseEnd);
//Start Drag Drop
DoDragDrop((sender as ListControl).SelectedValue, DragDropEffects.Copy);
if (_selectedItemIndex != -1)
{
// If the drag/drop was successful, there dropped text must be selected
if (!String.IsNullOrWhiteSpace(Globals.ThisAddIn.Application.Selection.Text))
{
// Replace the selected text with a merge field MergeFieldHelper.InsertSingleMergeField(mergeFieldInfos[_selectedItemIndex].Name);
}
}
}
}
}