Imports Microsoft.VisualBasic
Imports System
Imports System.Runtime.InteropServices

Namespace ToolboxSnippetsInstaller
	Friend Class MessageFilter : Implements IOleMessageFilter
		'
        ' Publiczne API

		Public Shared Sub Register()
			Dim newfilter As IOleMessageFilter = New MessageFilter()

			Dim oldfilter As IOleMessageFilter = Nothing
			CoRegisterMessageFilter(newfilter, oldfilter)
		End Sub

		Public Shared Sub Revoke()
			Dim oldfilter As IOleMessageFilter = Nothing
			CoRegisterMessageFilter(Nothing, oldfilter)
		End Sub

		'
        ' Implementacja IOleMessageFilter

		Private Function HandleInComingCall(ByVal dwCallType As Integer, ByVal hTaskCaller As System.IntPtr, ByVal dwTickCount As Integer, ByVal lpInterfaceInfo As System.IntPtr) As Integer Implements IOleMessageFilter.HandleInComingCall
			System.Diagnostics.Debug.WriteLine("IOleMessageFilter::HandleInComingCall")

			Return 0 'SERVERCALL_ISHANDLED
		End Function

		Private Function RetryRejectedCall(ByVal hTaskCallee As System.IntPtr, ByVal dwTickCount As Integer, ByVal dwRejectType As Integer) As Integer Implements IOleMessageFilter.RetryRejectedCall
			System.Diagnostics.Debug.WriteLine("IOleMessageFilter::RetryRejectedCall")

			If dwRejectType = 2 Then 'SERVERCALL_RETRYLATER
				System.Diagnostics.Debug.WriteLine("Retry call later")
                Return 99 'podjęcie ponownej próby, jeśli wartość zwracana >=0 & <100
			End If
            Return -1 'anulowanie wywołania
		End Function

		Private Function MessagePending(ByVal hTaskCallee As System.IntPtr, ByVal dwTickCount As Integer, ByVal dwPendingType As Integer) As Integer Implements IOleMessageFilter.MessagePending
			System.Diagnostics.Debug.WriteLine("IOleMessageFilter::MessagePending")

			Return 2 'PENDINGMSG_WAITDEFPROCESS
		End Function

		'
        ' Implementacja

		<DllImport("Ole32.dll")> _
		Private Shared Function CoRegisterMessageFilter(ByVal newfilter As IOleMessageFilter, <System.Runtime.InteropServices.Out()> ByRef oldfilter As IOleMessageFilter) As Integer
		End Function
	End Class

    <ComImport(), Guid("00000016-0000-0000-C000-000000000046"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _
    Interface IOleMessageFilter ' celowa zmiana nazwy, by uniknąć pomylenia z System.Windows.Forms.IMessageFilter
        <PreserveSig()> _
        Function HandleInComingCall(ByVal dwCallType As Integer, ByVal hTaskCaller As IntPtr, ByVal dwTickCount As Integer, ByVal lpInterfaceInfo As IntPtr) As Integer

        <PreserveSig()> _
        Function RetryRejectedCall(ByVal hTaskCallee As IntPtr, ByVal dwTickCount As Integer, ByVal dwRejectType As Integer) As Integer

        <PreserveSig()> _
        Function MessagePending(ByVal hTaskCallee As IntPtr, ByVal dwTickCount As Integer, ByVal dwPendingType As Integer) As Integer
    End Interface
End Namespace
