This project has moved and is read-only. For the latest updates, please go here.

Outlook Explorer BeforeItemPasteEvent: Hot access the pasted item?

Jan 5, 2017 at 9:29 PM

I have an Outlook VBA project which I want to convert to a .Net addin, using NetOffice 1.7.3 and Visual Studio Express 2013. So far 90% is finished and running smoothly, but now I'm scratching my head. I'm using the BeforeItemPasteEvent:
m_objExplorer.BeforeItemPasteEvent += new Outlook.Explorer_BeforeItemPasteEventHandler(BeforeItemPasteEvent);
It passes the pasted object as COMObject:
public void TaskBeforeItemPaste(ref object ClipBoard)
In my old VBA project I could easily access this object:
Public Sub TaskBeforeItemPaste(ClipboardContent As Variant)
    Dim Appt As Outlook.TaskItem
    Dim t As String
    t = ClipboardContent.Item(1).MessageClass
    If t = "IPM.Task" Then
        Set Appt = ClipboardContent.Item(1)
        Appt.Role = t 'Set flag
    End If
End Sub
This easy access to the pasted item seems not to be possible with the COMObject which I get with the BeforeItemPasteEventHandler. I googled a lot and got as far as using the IDispatch interface and confirming the type of the passed object. But I'm completely out of my depth here when trying to use the IDispatch.Invoke method. Up to now I get an access violation exception. And even if I get around that, I wouldn't trust myself to write code which doesn't cause security issues, memory leaks or other problems.
Is there an easy way to get the pasted item from 'ref object ClipBoard' and change it before it's actually pasted?

Jan 6, 2017 at 5:01 PM
I found the solution. When an Explorer fires the BeforeItemPasteEvent the Explorer's 'Selection' property contains the selection which is also passed in the COMObject 'ClipboardContent'. So instead of bothering with the passed COMObject, I work with the Explorer property.

For an event handler which is defined like this:
m_objExplorer.BeforeItemPasteEvent += new Outlook.Explorer_BeforeItemPasteEventHandler(BeforeItemPasteEvent);
My code would be this:
public void TaskBeforeItemPaste(ref object ClipBoard)
    IEnumerator<object> enumerator = m_objExplorer.Selection.GetEnumerator();
    if (enumerator.MoveNext())
        object item = enumerator.Current;
        if (item.GetType() == typeof(Outlook.TaskItem))
            Outlook.TaskItem task = (Outlook.TaskItem)item;
            task.Role = "IPM.Task";
Marked as answer by CTreffler on 1/6/2017 at 9:01 AM