Clipboard Changed Event

devimore

Member
Joined
Jul 1, 2010
Messages
9
Programming Experience
5-10
Hey, everyone
I have a big problem

So im making a clipboard application, that collects and saves clipboard to files, so i can use saved clipboard later..
I have this code. It works perfectly, but..
Because of the headnler set to ME (or form1) this code dosn't work when form is not visible or active
But i need this code to work when form is hidden.. Because my app is running in system tray.

Can anybody help me?

Here is the code:
VB.NET:
Imports System.Runtime.InteropServices

 Private Const WM_DRAWCLIPBOARD As Integer = &H308
    Private Const WM_CHANGECBCHAIN As Integer = &H30D

    Private mNextClipBoardViewerHWnd As IntPtr
    Private Event OnClipboardChanged()

    <DllImport("user32")> _
    Private Shared Function SetClipboardViewer(ByVal hWnd As IntPtr) As IntPtr
    End Function

    <DllImport("user32")> _
    Private Shared Function ChangeClipboardChain(ByVal hWnd As IntPtr, ByVal hWndNext As IntPtr) As _
        <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

    <DllImport("user32")> _
    Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, _
        ByVal lParam As IntPtr) As IntPtr
    End Function

    Sub New()
        InitializeComponent()
        mNextClipBoardViewerHWnd = SetClipboardViewer(Me.Handle)
        AddHandler Me.OnClipboardChanged, AddressOf ClipBoardChanged
    End Sub

    Protected Overrides Sub WndProc(ByRef m As Message)
        Select Case m.Msg
            Case WM_DRAWCLIPBOARD
                RaiseEvent OnClipboardChanged()
                SendMessage(mNextClipBoardViewerHWnd, m.Msg, m.WParam, m.LParam)

            Case WM_CHANGECBCHAIN
                If m.WParam.Equals(mNextClipBoardViewerHWnd) Then
                    mNextClipBoardViewerHWnd = m.LParam
                Else
                    SendMessage(mNextClipBoardViewerHWnd, m.Msg, m.WParam, m.LParam)
                End If
        End Select
        MyBase.WndProc(m)
    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles Me.FormClosing
        ChangeClipboardChain(Me.Handle, mNextClipBoardViewerHWnd)
    End Sub

	Public Sub ClipBoardChanged()
		'Clipboard has changed
	End Sub
 
Each time you set ShowInTaskbar the window handle for the form is recreated, so the window handle you added to clipboard chain is no longer valid. To remedy this you can add to chain on HandleCreated event and remove from chain on HandleDestroyed event. Another option is using a window handle that doesn't change, for example an internal NativeWindow. Attached is a ClipboardViewer component class that does this. Usage: you can add this class to a project and rebuild, then find it in Toolbox in project components section and add to form. Doubleclick it to get the ClipboardChanged event.
 

Attachments

  • ClipboardViewer.zip
    1 KB · Views: 126
Back
Top