65.9K
CodeProject is changing. Read more.
Home

Drag and Drop from Custom Task Pane to Microsoft Office Documents

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Jan 31, 2014

CPOL

1 min read

viewsIcon

19089

downloadIcon

575

This tip briefly explains drag and drop text from custom task pane to Excel\Word\Powerpoint

Introduction

Have you ever needed a text to be dragged and dropped into Office documents from your custom task pane? If yes, go ahead.

Background

In this tip, I refer to Excel, Word and Powerpoint 2010 as Office documents. Basically, Office documents allow drag and drop (D&D) content within the applications, across the Office applications and from other text editors like Wordpad, Microsoft Visual Studio, etc.

My previous article ResizeCustomTaskPane states the prerequisites that user should know before implementing this tip. Let us see simple D&D text from custom task pane.

Using the Code

Architecture and source code are the same as my previous article and to save time, I have explained only the heart of the code. Refer to the following image of this sample.

The taskpane has 4 buttons and all the button's mousedown events are hooked to a single function.

private void button1_MouseDown(object sender, MouseEventArgs e)    {
            if (MouseButtons == MouseButtons.Left)
            {
                string strValue = "I am " + (sender as Button).Text;
                if (OfficeType == OfficeAPPType.EXCEL || OfficeType == OfficeAPPType.WORD)
                                {
                                    (sender as Button).DoDragDrop(strValue, DragDropEffects.All);
                                }
                                else if (OfficeType == OfficeAPPType.PPT)
                                {
                                    if (m_rich == null)
                                        m_rich = new RichTextBox();
                    m_rich.Text = strValue;
                    IDataObject data = new DataObject();
                                        data.SetData(DataFormats.Rtf, m_rich.Rtf);
                    (sender as Button).DoDragDrop(data, DragDropEffects.All);                    
                                    }                 
                                }
                            } 

D&D for Powerpoint is little trickier than Excel and Word. Both Excel and Word support DataFormats.Text, so we can directly supply string value to DoDragDrop function. Powerpoint needs DataFormats.Rtf format, so supply IDataObject with RTF text. Here I used RichTextBox to get the RTF text. That's all we need to drag and drop the text from taskpane. Ideas better than this are always welcome. Smile | :)