Buenas, llevo todo el dia intentando obtener el titulo de la ventana que tienes abierta pero no lo he conseguido, e aqui mi intento:
Public Class Form1
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
Private Function findPartialTitle(ByVal partialTitle As String) As IntPtr
For Each p As Process In Process.GetProcesses()
If p.MainWindowTitle.IndexOf(partialTitle, 0, StringComparison.CurrentCultureIgnoreCase) > -1 Then
'
'We found a match, so return the handle to the window
'
Return p.MainWindowHandle
End If
Next
'
'If no match, return NULL (or close enough)
'
Return IntPtr.Zero
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim hwnd As Long = findPartialTitle("YouTube")
Dim lngLen As Integer = 512
Dim MyStr As String
'Create a buffer
MyStr = 255
'Get the window's text
GetWindowText(hwnd, MyStr, 254)
MsgBox("La ventana abierta no es correcta, intentalo de nuevo: " &MyStr)
End Sub
End Class
El error al depurar es en esta linea:
GetWindowText(hwnd, MyStr, 254)
GetForeGroundWindow()
Retrieves a handle to the foreground window (the window with which the user is currently working). The system assigns a slightly higher priority to the thread that creates the foreground window than it does to other threads.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms633505(v=vs.85).aspx
Gracias pero el caso es que esa función no la reconoce, uso visual studio 2010
Si no me equivoco eso es .net y hay un subforo para ello.
Aqui va el codigo
Private Declare Function GetWindowText Lib "User32" Alias "GetWindowTextA" (ByVal hWnd As Long,ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function GetForegroundWindow Lib "User32" () As Long
public function TextoVentanaActiva() as string
Dim hwnd_Ventana As Long
Dim Caption_Ventana As String
Dim length As Long
' Captura el Hwnd de la ventana activa
hwnd_Ventana = GetForegroundWindow()
'Crea un Buffer
Caption_Ventana = Space$(1024)
' Retorna la cantidad de caracteres
length = GetWindowText(hwnd_Ventana, Caption_Ventana, Len(Caption_Ventana))
' Obtiene solo el caption sin los espacios nulos de la cadena
TextoVentanaActiva = Left$(Caption_Ventana, length)
end function
Me sigue tirando error al empezar el programa con debug en esta linea :S
Dice: Se detectó PInvokeStackImbalance
length = GetWindowText(hwnd_Ventana, Caption_Ventana, Len(Caption_Ventana))