I am using ManagementEventWatcher to get message when process start and stop.
I am successfully getting message when word process start it displays me File name and datetime.
I have an issue in stopping process.
Public Class Form1
Dim list As New List(Of String)
Dim list1 As New List(Of String)
Private processStartEvent As ManagementEventWatcher = New ManagementEventWatcher("SELECT * FROM Win32_ProcessStartTrace")
Private processStopEvent As ManagementEventWatcher = New ManagementEventWatcher("SELECT * FROM Win32_ProcessStopTrace")
Public Sub New()
InitializeComponent()
AddHandler processStartEvent.EventArrived, New EventArrivedEventHandler(AddressOf processStartEvent_EventArrived)
processStartEvent.Start()
AddHandler processStopEvent.EventArrived, New EventArrivedEventHandler(AddressOf processStopEvent_EventArrived)
processStopEvent.Start()
End Sub
Private Sub processStartEvent_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs)
Dim allProcesses = Process.GetProcesses().Where(Function(p) p.ProcessName.Contains("WINWORD"))
Dim windowTitles = ChildWindowManager.GetChildWindowTitles(allProcesses.First().Id)
For Each title In windowTitles
If (title.Contains("- Word")) Then
If Not (title.Contains("Opening - Word")) Then
If Not list.Contains(title) Then
list.Add(title)
MessageBox.Show("+ Process Started. File Name: " & String.Join(",", list.Item(list.Count - 1)) & " | Date & Time: " & System.DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") & vbNewLine & vbNewLine)
End If
End If
End If
Next
End Sub
Private Sub processStopEvent_EventArrived(ByVal sender As Object, ByVal e As EventArrivedEventArgs)
End Sub
End Class
Class ChildWindowManager
Delegate Function EnumThreadDelegate(ByVal hWnd As IntPtr, ByVal lParam As IntPtr) As Boolean
<DllImport("user32.dll")>
Private Shared Function EnumThreadWindows(ByVal dwThreadId As Integer, ByVal lpfn As EnumThreadDelegate, ByVal lParam As IntPtr) As Boolean
End Function
<DllImport("user32.dll")>
Public Shared Function GetWindowText(ByVal hwnd As Integer, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer
End Function
<DllImport("user32.dll")>
Private Shared Function GetWindowTextLength(ByVal hwnd As IntPtr) As Integer
End Function
Private Shared Function EnumerateProcessWindowHandles(ByVal processId As Integer) As List(Of IntPtr)
Dim windowHandles = New List(Of IntPtr)()
For Each thread As ProcessThread In Process.GetProcessById(processId).Threads
EnumThreadWindows(thread.Id, Function(hWnd, lParam)
windowHandles.Add(hWnd)
Return True
End Function, IntPtr.Zero)
Next
Return windowHandles
End Function
Private Shared Function GetWindowTitle(ByVal hWnd As IntPtr) As String
Dim length As Integer = GetWindowTextLength(hWnd)
If length = 0 Then Return Nothing
Dim titleStringBuilder As New System.Text.StringBuilder("", length)
GetWindowText(hWnd, titleStringBuilder, titleStringBuilder.Capacity + 1)
Return titleStringBuilder.ToString()
End Function
Public Shared Function GetChildWindowTitles(processId As Integer) As List(Of String)
Dim windowTitles As New List(Of String)
For Each Handle In EnumerateProcessWindowHandles(processId)
Dim windowText = GetWindowTitle(Handle)
If windowText <> Nothing Then
windowTitles.Add(windowText)
End If
Next
Return windowTitles
End Function
End Class
Related
Hey all I am using some UIAutomation code that was written in C#. So I converted it into VB.net so that I could integrate it into my own program I am making.
The code that has the error is this line:
Private Sub LogMessage(message As String)
Dispatcher.BeginInvoke(DispatcherPriority.Normal, New SetMessageCallback(AddressOf DisplayLogMessage), message)
End Sub
The error is on the Dispatcher.BeginInvoke stating Error 1 Reference to a non-shared member requires an object reference..
The code in C# looks like this:
private void LogMessage(string message)
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new SetMessageCallback(DisplayLogMessage), message);
}
And has no errors and works just fine.
What am I missing from the VB.net version to make it work correctly?
The original C# code can be found HERE.
My converted C# to VB.net code looks like this:
Imports System.Threading
Imports Automation = System.Windows.Automation
Imports System.Windows.Automation
Imports System.Windows.Threading
Public Class Form1
Public Delegate Sub SetMessageCallback(ByVal [_Msg] As String)
Private Sub Automate()
LogMessage("Getting RootElement...")
Dim rootElement As AutomationElement = AutomationElement.RootElement
If rootElement IsNot Nothing Then
LogMessage("OK." + Environment.NewLine)
Dim condition As Automation.Condition = New PropertyCondition(AutomationElement.NameProperty, "UI Automation Test Window")
LogMessage("Searching for Test Window...")
Dim appElement As AutomationElement = rootElement.FindFirst(TreeScope.Children, condition)
If appElement IsNot Nothing Then
LogMessage("OK " + Environment.NewLine)
LogMessage("Searching for TextBox A control...")
Dim txtElementA As AutomationElement = GetTextElement(appElement, "txtA")
If txtElementA IsNot Nothing Then
LogMessage("OK " + Environment.NewLine)
LogMessage("Setting TextBox A value...")
Try
Dim valuePatternA As ValuePattern = TryCast(txtElementA.GetCurrentPattern(ValuePattern.Pattern), ValuePattern)
valuePatternA.SetValue("10")
LogMessage("OK " + Environment.NewLine)
Catch
WriteLogError()
End Try
Else
WriteLogError()
End If
LogMessage("Searching for TextBox B control...")
Dim txtElementB As AutomationElement = GetTextElement(appElement, "txtB")
If txtElementA IsNot Nothing Then
LogMessage("OK " + Environment.NewLine)
LogMessage("Setting TextBox B value...")
Try
Dim valuePatternB As ValuePattern = TryCast(txtElementB.GetCurrentPattern(ValuePattern.Pattern), ValuePattern)
valuePatternB.SetValue("5")
LogMessage("OK " + Environment.NewLine)
Catch
WriteLogError()
End Try
Else
WriteLogError()
End If
Else
WriteLogError()
End If
End If
End Sub
Private Function GetTextElement(parentElement As AutomationElement, value As String) As AutomationElement
Dim condition As Automation.Condition = New PropertyCondition(AutomationElement.AutomationIdProperty, value)
Dim txtElement As AutomationElement = parentElement.FindFirst(TreeScope.Descendants, condition)
Return txtElement
End Function
Private Sub DisplayLogMessage(message As String)
TextBox1.Text += message
End Sub
Private Sub LogMessage(message As String)
Me.Dispatcher.BeginInvoke(DispatcherPriority.Normal, New SetMessageCallback(AddressOf DisplayLogMessage), message)
End Sub
Private Sub WriteLogError()
LogMessage("ERROR." + Environment.NewLine)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim automateThread As New Thread(New ThreadStart(AddressOf Automate))
automateThread.Start()
End Sub
End Class
Found the correct way of doing it:
Private Sub LogMessage(message As String)
Me.BeginInvoke(New SetMessageCallback(AddressOf DisplayLogMessage), message)
End Sub
Thanks goes to #HansPassant for the help.
Dispatcher can be static. I think you need Me.Dispatcher.
IE 9 is setting cookie values in browser even after changing privacy settings. What is the next option to save cookies in IE?
see below my code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not Request.Cookies("RememberMe") Is Nothing Then
'this if condition is failing, it never executes and working in chrome.
End If
End If
Response.Cache.SetExpires(DateTime.Parse(DateTime.Now.ToString()))
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetNoStore()
Response.AppendHeader("Pragma", "no-cache")
End Sub
Protected Sub imgLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If Page.IsValid() Then
If Not user Is Nothing Then
FormsAuthentication.RedirectFromLoginPage(strUserID, False)
If (chkRememberMe.Checked) Then
Helper.StoreRememberMe(strUserID, ddlCompany.SelectedItem.Text)
ElseIf Not Request.Cookies("RememberMe") Is Nothing Then
Helper.DeleteCookie("RememberMe")
End If
Session("userInfo") = user
Response.Redirect("~/home.aspx")
End If
End If
End Sub
Public Shared Sub StoreRememberMe(ByVal username As String, ByVal company As String)
Dim rememberMe As New HttpCookie("RememberMe")
rememberMe.Values.Add("user", username)
rememberMe.Values.Add("company", company)
rememberMe.Expires = DateTime.Now.AddDays(30)
'cookie Expires ;
HttpContext.Current.Response.AppendCookie(rememberMe)
End Sub
I am using microsoft POS for .net dll and I am converting this part to vb.net from a HOL sample barcode reading tutorial written in c# found here.
EDIT:The device list shows and popup window shows (the activate button is pressed and scanner input is tested)but the txteventhistory is not update even when scanner emulator is used and i suspect the said part is the culprit. thank you for the response
{
Action<string> updateEventHistoryAction = new Action<string>(p => { txtEventHistory.Text = p; });
txtEventHistory.Invoke(updateEventHistoryAction, newEvent);
}
from this
void activeScanner_DataEvent(object sender, DataEventArgs e)
{
UpdateEventHistory("Data Event");
ASCIIEncoding encoder = new ASCIIEncoding();
try
{
// Display the ASCII encoded label text
string data = encoder.GetString(activeScanner.ScanDataLabel);
Action<string> updateScanDataLabelAction = new Action<string>(p => {txtScanDataLabel.Text = p;});
txtScanDataLabel.Invoke(updateScanDataLabelAction, data);
// Display the encoding type
string dataType = activeScanner.ScanDataType.ToString();
Action<string> updateScanDataTypeLabelAction = new Action<string>(p => { txtScanDataType.Text = p; });
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType);
// re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = true;
}
catch (PosControlException)
{
// Log any errors
UpdateEventHistory("DataEvent Operation Failed");
}
}
the conversion tool in #develop yielded the one below but i don't think it's correct
Dim updateScanDataLabelAction As New Action(Of String)(function (p)
txtScanDataLabel.Text = p
end function)
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
I tried converting it to but not quite there i think, though it
Private Sub activeScanner_DataEvent(sender As Object, e As DataEventArgs)
UpdateEventHistory("Data Event")
Dim encoder As New ASCIIEncoding()
Try
' Display the ASCII encoded label text
Dim data As String = encoder.GetString(activeScanner.ScanDataLabel)
Dim updateScanDataLabelAction append As New Action(Of String))
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType)
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("DataEvent Operation Failed")
End Try
End Sub
Private Sub p(ByVal text As String)
txtScanDataType.Text = text
End Sub
here is the whole code
Imports Microsoft.PointOfService
Imports System.Collections
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Namespace POS
Partial Public Class ScannerLab
Inherits Form
Private explorer As PosExplorer
Private scannerList As DeviceCollection
Private scannerList1 As DeviceCollection
Private activeScanner As Scanner
Public Sub New()
InitializeComponent()
End Sub
Private Sub ScannerLab_Load(ByVal sender As Object, ByVal e As EventArgs)handles mybase.load
explorer = New PosExplorer()
scannerList1 = explorer.GetDevices()
bsdevices.DataSource = scannerList1
cboDevices.DisplayMember = scannerList1.ToString()
scannerList = explorer.GetDevices(DeviceType.Scanner)
devicesBindingSource.DataSource = scannerList
lstDevices.DisplayMember = scannerList.ToString()
End Sub
Private Sub btnActivateDevice_Click(ByVal sender As Object, ByVal e As EventArgs) handles btnActivateDevice.Click
If lstDevices.SelectedItem IsNot Nothing Then
ActivateScanner(DirectCast(lstDevices.SelectedItem, DeviceInfo))
End If
End Sub
Private Sub reportFailure()
Throw New Exception("The method or operation is not implemented.")
End Sub
Private Sub ActivateScanner(ByVal selectedScanner As DeviceInfo)
'Verifify that the selectedScanner is not null
' and that it is not the same scanner already selected
If selectedScanner IsNot Nothing AndAlso Not selectedScanner.IsDeviceInfoOf(activeScanner) Then
' Configure the new scanner
DeactivateScanner()
' Activate the new scanner
UpdateEventHistory(String.Format("Activate Scanner: {0}", selectedScanner.ServiceObjectName))
Try
activeScanner = DirectCast(explorer.CreateInstance(selectedScanner), Scanner)
activeScanner.Open()
activeScanner.Claim(1000)
activeScanner.DeviceEnabled = True
AddHandler activeScanner.DataEvent, AddressOf activeScanner_DataEvent
AddHandler activeScanner.ErrorEvent, AddressOf activeScanner_ErrorEvent
activeScanner.DecodeData = True
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log error and set the active scanner to none
UpdateEventHistory(String.Format("Activation Failed: {0}", selectedScanner.ServiceObjectName))
activeScanner = Nothing
End Try
End If
End Sub
Private Sub DeactivateScanner()
If activeScanner IsNot Nothing Then
' We have an active scanner, lets log that we are
' about to close it.
UpdateEventHistory("Deactivate Current Scanner")
Try
' Close the active scanner
activeScanner.Close()
Catch generatedExceptionName As PosControlException
' Log any error that happens
UpdateEventHistory("Close Failed")
Finally
' Don't forget to set activeScanner to null to
' indicate that we no longer have an active
' scanner configured.
activeScanner = Nothing
End Try
End If
End Sub
Private Sub activeScanner_DataEvent(ByVal sender As Object, ByVal e As DataEventArgs)
UpdateEventHistory("Data Event")
Dim encoder As New ASCIIEncoding()
Try
' Display the ASCII encoded label text
Dim data As String = encoder.GetString(activeScanner.ScanDataLabel)
Dim updateScanDataLabelAction As New Action(Of String)(AddressOf p)
txtScanDataLabel.Invoke(updateScanDataLabelAction, data)
' Display the encoding type
Dim dataType As String = activeScanner.ScanDataType.ToString()
Dim updateScanDataTypeLabelAction As New Action(Of String)(AddressOf p)
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType)
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("DataEvent Operation Failed")
End Try
End Sub
Private Sub p(ByVal text As String)
txtScanDataType.Text = text
End Sub
Private Sub q(ByVal text As String)
txtScanDataType.Text = text
End Sub
Private Sub UpdateEventHistory(ByVal newEvent As String)
If txtEventHistory.InvokeRequired Then
Dim updateEventHistoryAction As New Action(Of String)(AddressOf q)
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
Else
txtEventHistory.Text = (Convert.ToString(newEvent) & System.Environment.NewLine) + txtEventHistory.Text
End If
End Sub
Private Sub activeScanner_ErrorEvent(ByVal sender As Object, ByVal e As DeviceErrorEventArgs)
UpdateEventHistory("Error Event")
Try
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("ErrorEvent Operation Failed")
End Try
End Sub
EDIT: updated the code
I'm doing a desktop academic project one of the requirment of this project is to allert the user on mobile by sms and this sms should be sent by a mobile that is connected with the pc. I don't know the way how can i do it. When i did google search here i got the gsm modems gateways one kind of solution to send sms through pc. But they are not free. Then Nokia Conectivity SDK is another way but it is not compatible with Visual Studio2010. I got this example on a website but the sender had said at the end there are errors in my code.
Option Explicit On
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.load
End Sub
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _Continue As Boolean = False
Shared _ContSMS As Boolean = False
Private _Wait As Boolean = False
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New(ByRef COMMPORT As String)
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 9600
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
ReadThread = New Thread(AddressOf ReadPort)
End Sub
Public Function SendSMS(ByVal CellNumber As String, ByVal SMSMessage As String) As Boolean
Dim MyMessage As String = Nothing
'Check if Message Length <= 160
If SMSMessage.Length <= 160 Then
MyMessage = SMSMessage
Else
MyMessage = Mid(SMSMessage, 1, 160)
End If
If IsOpen = True Then
SMSPort.WriteLine("AT+CMGS=" & CellNumber & vbCr)
_ContSMS = False
SMSPort.WriteLine(MyMessage & vbCrLf & Chr(26))
_Continue = False
RaiseEvent Sending(False)
End If
End Function
Private Sub ReadPort()
Dim SerialIn As String = Nothing
Dim RXBuffer(SMSPort.ReadBufferSize) As Byte
Dim SMSMessage As String = Nothing
Dim Strpos As Integer = 0
Dim TmpStr As String = Nothing
While SMSPort.IsOpen = True
If (SMSPort.BytesToRead <> 0) And (SMSPort.IsOpen = True) Then
While SMSPort.BytesToRead <> 0
SMSPort.Read(RXBuffer, 0, SMSPort.ReadBufferSize)
SerialIn = SerialIn & System.Text.Encoding.ASCII.GetString(RXBuffer)
If SerialIn.Contains(">") = True Then
_ContSMS = True
End If
If SerialIn.Contains("+CMGS:") = True Then
_Continue = True
RaiseEvent Sending(True)
_Wait = False
SerialIn = String.Empty
ReDim RXBuffer(SMSPort.ReadBufferSize)
End If
End While
RaiseEvent DataReceived(SerialIn)
SerialIn = String.Empty
ReDim RXBuffer(SMSPort.ReadBufferSize)
End If
End While
End Sub
Public ReadOnly Property IsOpen() As Boolean
Get
If SMSPort.IsOpen = True Then
IsOpen = True
Else
IsOpen = False
End If
End Get
End Property
Public Sub Open()
If IsOpen = False Then
SMSPort.Open()
ReadThread.Start()
End If
End Sub
Public Sub Close()
If IsOpen = True Then
'SMSPort = New SMSCOMMS("COM1")
'SMSEngine.Open()
'SMSEngine.SendSMS("919888888888", "SMS Testing")
'SMSEngine.Close()
SMSPort.Close()
End If
End Sub
End Class
but it is in vb.net i have not command in it. is it work?
Kindly Give me some idea, example I'm doing it in winform using c sharp.
hey i used GSMCOMM library and that works for me to send and receive sms using Computer. download it from google and see its examples to check how it works.
here are some links that help
GSMCOMM Send and recieve SMS Using GSM Modem
from here you can download GSMCOMM library
I'm not sure if you want a way to connect to a phone or a way to send an sms from a pc so I'll give both.
To connect to a phone (if it has data and an android or IOS or something where you can directly modify code) you can create a socket connection from your pc to your phone. I have done this in android aps before and it works good.
If you simply need to send an sms from your computer and you know the carrier just send an email using this list http://www.mutube.com/projects/open-email-to-sms/gateway-list/
Does anybody know how I can get the URL of any open IE processes on a computer?
I don't need to manipulate the IE instance at all -- just get information about the page that's currently loaded.
Thanks!
This appears to be one way of doing it (code is Visual Basic, sorry, but it shows the principle):
Private Declare Function GETWINDOWTEXT Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Integer, ByVal lpString As String, ByVal cch As Integer) As Integer
Private Declare Function SetForegroundWindow Lib "user32.dll" (ByVal hwnd As Integer) As Integer
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Integer, ByVal hWnd2 As Integer, ByVal lpsz1 As String, ByVal lpsz2 As String) As Integer
Private Declare Ansi Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As String) As Integer
Private Const WM_GETTEXT As Short = &HDS
Private Const WM_GETTEXTLENGTH As Short = &HES
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim hwnd As Integer = FindWindowEx(0, 0, "IEFrame", vbNullString)
If Not hwnd = 0 Then
SetForegroundWindow(hwnd)
Dim Worker As Integer = FindWindowEx(hwnd, 0, "WorkerW", vbNullString)
Dim ToolBar As Integer = FindWindowEx(Worker, 0, "ReBarWindow32", vbNullString)
Dim ComboBoxEx As Integer = FindWindowEx(ToolBar, 0, "ComboBoxEx32", vbNullString)
Dim txtLength As Long = SendMessage(ComboBoxEx, WM_GETTEXTLENGTH, CInt(0), CInt(0)) + 1 ' Get Length Of Text
Dim txtBuff As String = Space(txtLength)
Dim URL As Long = URL = SendMessage(ComboBoxEx, WM_GETTEXT, txtLength, txtBuff) 'Get URL From ComboBoxEx
MsgBox(txtBuff)
End If
End Sub
Basically, you're finding the IE window, then drilling down to find the combobox in which the URL is typed, and then getting whatever string is typed into it. Obviously this isn't a perfect approach (if somebody overwrites the URL but doesn't hit Enter, you wouldn't know it).
A simple solution, and it works:
http://omegacoder.com/?p=63
Start IE yourself through automation (i.e var oIE = WScript.CreateObject("InternetExplorer.Application", "IE_");) and listen to NavigateComplete2.
Peek inot ROT (running objects table) - I think IE documents should show up there - Win32/COM - http://msdn.microsoft.com/en-us/library/ms684004(VS.85).aspx
Just find all IE windows and take text from address well (see MusiGenesis answer for that).