Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

keep track of focus vb.net

Posted on 2006-04-04
14
Medium Priority
?
776 Views
Last Modified: 2008-01-09
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!!
 
0
Comment
Question by:TechMonster
  • 7
  • 7
14 Comments
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 16374106
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
 

Author Comment

by:TechMonster
ID: 16376265
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 16376466
"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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:TechMonster
ID: 16382030
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 16382082
Could you describe that in a little more detail?  I'm not following...   =\
0
 

Author Comment

by:TechMonster
ID: 16382426
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 16382496
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
 

Author Comment

by:TechMonster
ID: 16383038
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 16383066
Can't do it that way in VB.Net as it is using a system wide hook...
0
 

Author Comment

by:TechMonster
ID: 16385706
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
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 16386013
That is VB6 code...I haven't tried it in VB.Net yet...I'll see what I can do...
0
 

Author Comment

by:TechMonster
ID: 16393513
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
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 2000 total points
ID: 16397883
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
 

Author Comment

by:TechMonster
ID: 16430110
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

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

577 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question