keep track of focus vb.net

how do you keep track of focus for different applications?

When I click on "Go" in VB it's supposed to paste the contents from clipboard to whatever
the last application the user clicked on.  appActivate is only specific to a applicaiton.  

Help!!
 
TechMonsterAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mike TomlinsonMiddle School Assistant TeacherCommented:
Here is how to create a form that does not steal the focus (thus allowing your paste to work since the the app with the focus keeps the focus even when you click your button).  Set the TopMost property to true.

Imports System.Runtime.InteropServices

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private Const WS_EX_NOACTIVATE = &H8000000
    Private Const WM_MOVING = &H216

    Private Structure RECT
        Public Left As Integer
        Public Top As Integer
        Public Right As Integer
        Public Bottom As Integer
    End Structure

    Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
        Get
            Dim cp As CreateParams = MyBase.CreateParams
            cp.ExStyle = cp.ExStyle Or WS_EX_NOACTIVATE
            Return cp
        End Get
    End Property

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = WM_MOVING Then
            Dim r As RECT
            r = DirectCast(Marshal.PtrToStructure(m.LParam, GetType(RECT)), RECT)
            Me.Location = New Point(r.Left, r.Top)
        End If

        MyBase.WndProc(m)
    End Sub

End Class
0
TechMonsterAuthor Commented:
Not sure I follow this code.  
The users have a option button that will set the VB application to topmost or not.
THe program was designed to have users click in a application with mouse to activate the form than
click on the GO in VB.net.  The Go will paste some text into the last place the mouse was pointed.

The end goal is to somehow capture the focus from the previous mouse click.  

With the above code are you stating that I can create a form that will not steal the focus?  How do you think I can still use the topmost feature?

0
Mike TomlinsonMiddle School Assistant TeacherCommented:
"With the above code are you stating that I can create a form that will not steal the focus?  How do you think I can still use the topmost feature?"

Exactly...your form can be topmost and NOT steal the focus.  The user simply selects the form with the box they want to paste into so that the cursor is sitting there.  Then they click the "Go" button on your form and it will simply paste by putting want you want on the clipboard and then using SendKeys with Ctrl-V or by sending each letter that you want individually to paste with SendKeys.

It's that simple....

The code I posted keeps your form from stealing focus when you click on it.  Try it with Notepad or something.  =)
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

TechMonsterAuthor Commented:
Yeah, the code works as you said except I have 1 minor problem.
I have created text boxes by code which are created everytime I run through this program.  
Now after 1 run of the application the controls do not go back to the text boxes unless I close it out and re-launch.  

 'Creation of textboxes and labels.
            NewTextBox(i) = New TextBox
            NewTextBoxLabel1(i) = New Label
            Me.Controls.Add(NewTextBox(i))
            NewTextBox(i).BackColor = BackColor.LemonChiffon

            Me.Controls.Add(NewTextBoxLabel1(i))
            NewTextBoxLabel1(i).Text = nostars
any ideas?
0
Mike TomlinsonMiddle School Assistant TeacherCommented:
Could you describe that in a little more detail?  I'm not following...   =\
0
TechMonsterAuthor Commented:
Sure.  It seems that the application never regains focus.  If I minimize the form and maximize it works fine.
To regain focus in VB.Net2003 it should be a simple one liner "me.focus" or appActivate().  I was not able to implement either one.  I have a treeview when a node is calls the textbox creation function.  I have some buttons which were created using the toolbox in VB.net.  The buttons work fine.  The text boxes losses functionallity.  They still get created but when I type in the text box it reverts back to the last application I selected such as NotePad and puts it there.
0
Mike TomlinsonMiddle School Assistant TeacherCommented:
LOL....ok I follow you now.

This is a double edged sword.

The code I gave you makes it easy to paste into the "last focused app" because our app does not take the focus.

But because our app doesn't get the focus, controls that normally require focus (like a TextBox) won't behave well.

We would need to use a different approach other than the WS_EX_NOACTIVATE option.

I remember coding this type of thing in a different way awhile back...I'll see if I can find it.   =\
0
TechMonsterAuthor Commented:
here is a C++ or C code and sample code some guy suggested but I really have no clue how to make it work.
****************************************************************************
... simply any (and every) window that MS-Windows creates.

What was done is (1) In the application's initialization section, an event hook:
SetWinEventHook( EVENT_MIN, EVENT_MAX, NULL, (WINEVENTPROC)( sbWindowsEventHook ), 0, 0, 0 );

… and (2) Then the hook keeps the appropriate handle:

WINEVENTPROC sbWindowsEventHook(
                                HWINEVENTHOOK  hEvent,
                                DWORD   event,
                                HWND    hwnd,
                                LONG    idObject,
                                LONG    idChild,
                                DWORD   idEventThread,
                                DWORD   dwmsEventTime)
{
    switch ( event )
    {
    case EVENT_SYSTEM_FOREGROUND:
        // Remember this window as the paste-to window
        sbGetApp()->SetFocusWindow( hwnd );
        break;
    }

    return 0;
}

0
Mike TomlinsonMiddle School Assistant TeacherCommented:
Can't do it that way in VB.Net as it is using a system wide hook...
0
TechMonsterAuthor Commented:
Do you think your ShellHook will work?  I past the code and it doesn't reconize form1 or me.

 If curWnd <> Form1.hWnd Then
                            ' store the last activated window
                            lastWnd = curWnd
                        Else
                            ' we have switched back to our window
                            Form1.Cls()
                            Form1.Caption = "Activated @ " & Now
                            Form1.Print("Last Windows Handle = " & lastWnd)
                            Form1.Print("Last Windows Caption: " & GetWindowCaption(lastWnd))
0
Mike TomlinsonMiddle School Assistant TeacherCommented:
That is VB6 code...I haven't tried it in VB.Net yet...I'll see what I can do...
0
TechMonsterAuthor Commented:
Found this code from IMRAM and having a few errors.

Intercepting WM_ACTIVATE message for any window (detecting activation with hooks/subclassing)

http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/VB_DOT_NET/Q_21083100.html

uMsgNotify = RegisterWindowMessage("SHELLHOOK")

    ' This basically registers our window to receive the shell events
Call RegisterShellHookWindow = (Me.Handle)

UMsgNotify has an error that it expects a declaration
Call states Syntax error.

Using VB.NET2003...


0
Mike TomlinsonMiddle School Assistant TeacherCommented:
Like so...

Imports System.Runtime.InteropServices

Public Class Form1
    Inherits System.Windows.Forms.Form

    Public Enum ShellEvents
        HSHELL_WINDOWCREATED = 1
        HSHELL_WINDOWDESTROYED = 2
        HSHELL_ACTIVATESHELLWINDOW = 3
        HSHELL_WINDOWACTIVATED = 4
        HSHELL_GETMINRECT = 5
        HSHELL_REDRAW = 6
        HSHELL_TASKMAN = 7
        HSHELL_LANGUAGE = 8
        HSHELL_ACCESSIBILITYSTATE = 11
    End Enum

    Public Declare Function RegisterWindowMessage Lib "user32.dll" Alias "RegisterWindowMessageA" (ByVal lpString As String) As Integer
    Public Declare Function DeregisterShellHookWindow Lib "user32" (ByVal hWnd As IntPtr) As Integer
    Public Declare Function RegisterShellHookWindow Lib "user32" (ByVal hWnd As IntPtr) As Integer
    Public Declare Function GetForegroundWindow Lib "user32" () As IntPtr
    Public Declare Function SetForegroundWindow Lib "user32" Alias "SetForegroundWindow" (ByVal hWnd As IntPtr) As Integer

    Private uMsgNotify As Integer
    Private lastWindow As IntPtr

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        uMsgNotify = RegisterWindowMessage("SHELLHOOK")
        RegisterShellHookWindow(Me.Handle)
    End Sub

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If m.Msg = uMsgNotify Then
            Select Case m.WParam.ToInt32
                Case ShellEvents.HSHELL_WINDOWACTIVATED
                    Debug.WriteLine("window activated")
                    Dim curWindow As IntPtr = GetForegroundWindow()
                    If (Not curWindow.Equals(IntPtr.Zero)) AndAlso (Not curWindow.Equals(Me.Handle)) Then
                        lastWindow = curWindow
                    End If
            End Select
        End If
        MyBase.WndProc(m)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If Not lastWindow.Equals(IntPtr.Zero) Then
            SetForegroundWindow(lastWindow)
            System.Threading.Thread.Sleep(100)
            SendKeys.Send("Hello World...")
        End If
    End Sub

    Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        DeregisterShellHookWindow(Me.Handle)
    End Sub

End Class
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
TechMonsterAuthor Commented:
Have not had a chance to view this code.  I actually, gave up on it and just send a Alt Tab.
I am sure that the code above is it and I will keep it in my history files to review later.

thanks.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.