Sorry if someone just posts a link to the answer, but I was really struggling to google this.
I can't figure out how to detect mobile phones when they're plugged in and then access their storage. The former is just something I don't know where to start looking and the second befuddles me a little because I'm used to accessing storage with a drive letter. The phones I've used (iPhone 4S and a few different Samsung galaxy's and notes) don't have a drive letter. So where would I start?
I use C# but I'm comfortable with the dllimports etc.
I've now done this code from the thread I linked in a comment above, nice and easy to throw into a program.
using System;
using System.Management;
using System.Threading;
namespace USBDeviceTester
{
class Program
{
static void Main(string[] args)
{
Thread myThread = new Thread(new ThreadStart(ThreadWorker));
myThread.Start();
}
public static void ThreadWorker()
{
WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
ManagementEventWatcher insertWatcher = new ManagementEventWatcher(insertQuery);
insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent);
insertWatcher.Start();
WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");
ManagementEventWatcher removeWatcher = new ManagementEventWatcher(removeQuery);
removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent);
removeWatcher.Start();
// Do something while waiting for events
System.Threading.Thread.Sleep(20000000);
}
private static void DeviceInsertedEvent(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("");
Console.WriteLine(" --- DEVICE INSERTED ---");
Console.WriteLine("");
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
Console.WriteLine(property.Name + " = " + property.Value);
}
Console.WriteLine("");
}
static void DeviceRemovedEvent(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("");
Console.WriteLine(" --- DEVICE REMOVED ---");
Console.WriteLine("");
//ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
//foreach (var property in instance.Properties)
//{
// Console.WriteLine(property.Name + " = " + property.Value);
//}
}
}
}
Which returns information as so:
--- DEVICE REMOVED ---
--- DEVICE INSERTED ---
Availability =
Caption = Apple Mobile Device USB Driver
ClassCode =
ConfigManagerErrorCode = 0
ConfigManagerUserConfig = False
CreationClassName = Win32_USBHub
CurrentAlternateSettings =
CurrentConfigValue =
Description = Apple Mobile Device USB Driver
DeviceID = USB\VID_05AC&PID_12A0\3ABFD2ED02E3982B5F4455FD684716A6D4958A74
ErrorCleared =
ErrorDescription =
GangSwitched =
InstallDate =
LastErrorCode =
Name = Apple Mobile Device USB Driver
NumberOfConfigs =
NumberOfPorts =
PNPDeviceID = USB\VID_05AC&PID_12A0\3ABFD2ED02E3982B5F4455FD684716A6D4958A74
PowerManagementCapabilities =
PowerManagementSupported =
ProtocolCode =
Status = OK
StatusInfo =
SubclassCode =
SystemCreationClassName = Win32_ComputerSystem
SystemName = MyComputerName
USBVersion =
Related
I want to send SMS from my Application that is under developing on Windows Forms Application, The trouble to achieving this task is getting Port Number, I'm suffering by this issue over a week, kindly guide me, I'm sending uploading my code, one thing more is that I'm using Android OS on my cell phone where I have installed SIM card, and device vendor is HUAWEI. thanks a lot in advance......
private void button1_Click(object sender, EventArgs e)
{
GsmCommMain comm;
int portn = 0;
System.IO.Ports.SerialPort _srp = new System.IO.Ports.SerialPort();
try
{
Cursor.Current = Cursors.Cross;
System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort");
Cursor = Cursors.WaitCursor;
foreach (System.Management.ManagementObject queryObj in searcher.Get())
{
Cursor = Cursors.Hand;
StatusLabel.Text = "Just Enterd in foreach Block...";
if (queryObj != null)
{
Cursor = Cursors.UpArrow;
object captionObj = queryObj["DESCRIPTION"];//Model Name
object capdeviceid = queryObj["DEVICEID"];//Comm port
object MaxBaudRate = queryObj["MAXBAUDRATE"];
object connstatus = queryObj["STATUS"];
object ct = queryObj.ToString();
int timeoutsec = 300;
StatusLabel.Text = "USB Modem Condition Main Enter Na Ho Saki...";
if (captionObj.ToString().Contains("USB Modem"))
{
_srp.PortName = capdeviceid.ToString();
portn = Convert.ToInt32(capdeviceid.ToString().Substring(3));
label1.Text = _srp.PortName + " ,,, " + portn;
comm = new GsmComm.GsmCommunication.GsmCommMain(portn, Convert.ToInt32(MaxBaudRate), timeoutsec);
StatusLabel.Text = "USB Modem Condition Main Entry...";
comm.Open();
if (comm.IsOpen())
btnSMSConnect.BackColor = Color.Green;
MessageBox.Show("Not Opening..." );
StatusLabel.Text = "Not Opening...";
}
}
}
}
catch (Exception e15)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e15.Message);
btnSMSConnect.BackColor = Color.Transparent;
//comm.Close();
_srp.Close();
}
}
}
}
I am working on WMI(Windows Management Instrumentation) in C# and stuck at a point.
I have to create an application using WMI (C#) similar to File System Watcher.
I would like to get notified every time whenever within a particular folder a new file is created or deleted.
MY WQL query is :
SELECT * from _InstanceModificationEvent within 2 where TargetInstance ISA 'CIM_DataFile' and TargetInstance.Drive = 'C:' AND TargetInstance.Path='\\Test'
While running the query using wbemtest , it displays an Error message prompting Invalid Class.
Can someone please help me out regarding same?
In order to detect when a file is created , modified or deleted you must use the __InstanceOperationEvent WMI Class and the using the value of __Class property you can figure out out if the file was modified, deleted o created.
Try this sample
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
public class EventWatcherAsync
{
private void WmiEventHandler(object sender, EventArrivedEventArgs e)
{
// e.NewEvent
string wclass = ((ManagementBaseObject)e.NewEvent).SystemProperties["__Class"].Value.ToString();
string wop = string.Empty;
switch (wclass)
{
case "__InstanceModificationEvent":
wop = "Modified";
break;
case "__InstanceCreationEvent":
wop = "Created";
break;
case "__InstanceDeletionEvent":
wop = "Deleted";
break;
}
string wfilename = ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["FileName"].ToString();
if (!string.IsNullOrEmpty(((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Extension"].ToString()))
{
wfilename += "." + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Extension"].ToString();
}
Console.WriteLine(String.Format("The File {0} was {1}", wfilename, wop));
}
public EventWatcherAsync()
{
try
{
string ComputerName = "localhost";
string WmiQuery;
ManagementEventWatcher Watcher;
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "";
Conn.Password = "";
Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
//Check for changes in the path C:\Test
WmiQuery = #"Select * From __InstanceOperationEvent Within 1
Where TargetInstance ISA 'CIM_DataFile' and TargetInstance.Drive = 'C:' AND TargetInstance.Path='\\Test\\'";
Watcher = new ManagementEventWatcher(Scope, new EventQuery(WmiQuery));
Watcher.EventArrived += new EventArrivedEventHandler(this.WmiEventHandler);
Watcher.Start();
Console.Read();
Watcher.Stop();
}
catch (Exception e)
{
Console.WriteLine("Exception {0} Trace {1}", e.Message, e.StackTrace);
}
}
public static void Main(string[] args)
{
Console.WriteLine("Listening {0}", "__InstanceOperationEvent");
Console.WriteLine("Press Enter to exit");
EventWatcherAsync eventWatcher = new EventWatcherAsync();
Console.Read();
}
}
}
I have two network adapters in my machine. E.g. adapter A and adapter B. The A keeps connected
I want to monitor the connection status of adapter B. I mean, connected or disconnected status.
I tried the System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
But it doesn't work, since the adapter A connected.
Maybe WMI is helpful, but I don't have any experience about it, also didn't find much useful article.
Could any one help to show me
how to subscribe WMI event of the adapter A connection status in C#
You can use the Win32_NetworkAdapter WMI class and the NetConnectionStatus property with the __InstanceModificationEvent event.
The WQL sentence will look like so
Select * From __InstanceModificationEvent Within 1 Where TargetInstance ISA 'Win32_NetworkAdapter' AND TargetInstance.Name='Network adapter name'
Try this sample
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
public class EventWatcherAsync
{
private void WmiEventHandler(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("TargetInstance.Name : " + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Name"]);
//2 (0x2) Connected
//7 (0x7) Media disconnected
Console.WriteLine("TargetInstance.NetConnectionStatus : " + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["NetConnectionStatus"]);
}
public EventWatcherAsync()
{
try
{
string ComputerName = "localhost";
string WmiQuery;
ManagementEventWatcher Watcher;
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "";
Conn.Password = "";
Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
WmiQuery ="Select * From __InstanceModificationEvent Within 1 "+
"Where TargetInstance ISA 'Win32_NetworkAdapter' AND TargetInstance.Name='Tarjeta Mini de media altura WLAN Wireless-N DW1501' ";
Watcher = new ManagementEventWatcher(Scope, new EventQuery(WmiQuery));
Watcher.EventArrived += new EventArrivedEventHandler(this.WmiEventHandler);
Watcher.Start();
Console.Read();
Watcher.Stop();
}
catch (Exception e)
{
Console.WriteLine("Exception {0} Trace {1}", e.Message, e.StackTrace);
}
}
public static void Main(string[] args)
{
Console.WriteLine("Listening {0}", "__InstanceModificationEvent");
Console.WriteLine("Press Enter to exit");
EventWatcherAsync eventWatcher = new EventWatcherAsync();
Console.Read();
}
}
}
the goal is like i said in the Topic. I know there are a lot of articles on that specific Problem and i tried all most all of them.
But since non of them worked out for me, I'm now trying to find out why this one just works sometimes and sometimes nothing is happening although many things are printed.
So this is my code which right now should wait for a job to be printed and just tell me about it. Nothing more.
private void StartMonitor()
{
try
{
var opt = new ConnectionOptions { EnablePrivileges = true };
var scope = new ManagementScope("root\\CIMV2", opt);
scope.Connect();
var query = new WqlEventQuery("SELECT * FROM __InstanceOperationEvent WITHIN 60 WHERE TargetInstance ISA \"Win32_PrintJob\"");
var watcher = new ManagementEventWatcher(query);
Console.WriteLine("Ready to receive Printer Job events...");
var pjEvent = watcher.WaitForNextEvent();
if (pjEvent != null) Console.WriteLine("Event occured: " + pjEvent.Properties["PagesPrinted"]);
}
catch (ManagementException e)
{
Console.WriteLine(e.StackTrace);
Console.WriteLine(e.ErrorCode);
Console.WriteLine(e.ErrorInformation);
_Error = e.Message;
throw;
}
}
To get the progress of the printed pages for a particular job, try using a smaller polling interval and use the EventArrivedEventHandler delegate attached to the WMI event for handling the incoming data in a asynchronous way.
Try this sample.
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
public class EventWatcherAsync
{
private void WmiEventHandler(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("TargetInstance.Caption : " + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Caption"]);
Console.WriteLine("TargetInstance.JobStatus : " + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["JobStatus"]);
Console.WriteLine("TargetInstance.PagesPrinted : " + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["PagesPrinted"]);
Console.WriteLine("TargetInstance.Status : " + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Status"]);
}
public EventWatcherAsync()
{
try
{
string ComputerName = "localhost";
string WmiQuery;
ManagementEventWatcher Watcher;
ManagementScope Scope;
if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
{
ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = "";
Conn.Password = "";
Conn.Authority = "ntlmdomain:DOMAIN";
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
}
else
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
WmiQuery ="Select * From __InstanceOperationEvent Within 1 "+
"Where TargetInstance ISA 'Win32_PrintJob' ";
Watcher = new ManagementEventWatcher(Scope, new EventQuery(WmiQuery));
Watcher.EventArrived += new EventArrivedEventHandler(this.WmiEventHandler);
Watcher.Start();
Console.Read();
Watcher.Stop();
}
catch (Exception e)
{
Console.WriteLine("Exception {0} Trace {1}", e.Message, e.StackTrace);
}
}
public static void Main(string[] args)
{
Console.WriteLine("Listening {0}", "__InstanceOperationEvent");
Console.WriteLine("Press Enter to exit");
EventWatcherAsync eventWatcher = new EventWatcherAsync();
Console.Read();
}
}
}
To get the total pages printed by a job I would try monitoring __InstanceDeletionEvents, I believe that at that time Win32_PrintJob.TotalPages should show the printed pages accurately (can't test this right now, sorry). There is also a nice alternative here:
Monitoring a Printer Queue from VB.NET
If you look at the article comments, the author also advises to monitor JOB_WRITTEN events to get the total number of pages printed.
If you are trying to monitor the progress of large print jobs, try monitoring __InstanceModificationEvents once the job is created, something like this:
Select * From __InstanceModificationEvent Within 1
Where TargetInstance Isa "Win32_PrintJob"
And TargetInstance.PagesPrinted > PreviousInstance.PagesPrinted
I want to get my network interface's Name, Speed, and MAC Address.
var searcher = new ManagementObjectSearcher { Scope = GetConnectedScope(target, "cimv2") };
try
{
searcher.Query = new ObjectQuery("SELECT MACAddress, Speed, Name FROM Win32_NetworkAdapter");
var nicList = new List<NetworkInterfaceModel>();
foreach (var item in searcher.Get())
{
nicList.Add(new NetworkInterfaceModel
{
NetworkInterfaceName = (string)item["Name"],
NetworkInterfaceSpeed = (double)(item["Speed"] != null ? (ulong) item["Speed"] : 0)/1000/1000,
MacAddress = (string)item["MACAddress"]
});
}
For Windows 7 and Vista it work just fine, but for XP and Windows Server 2003 it didn't collect the speed. How can I get the speed for XP and Server 2003?
You can get networks name using windows cmd:
Process p = new Process();
p.StartInfo.FileName = "netsh.exe";
p.StartInfo.Arguments = "wlan show interfaces";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string s = p.StandardOutput.ReadToEnd();
string s1 = s.Substring(s.IndexOf("SSID"));
s1 = s1.Substring(s1.IndexOf(":"));
s1 = s1.Substring(2, s1.IndexOf("\n")).Trim();
p.WaitForExit();
namelabel.Text = s1;
for MAC Address:
IPAddress IP = IPAddress.Parse("192.168.1.1");
byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;
UInt32 nRet = 0;
uint nAddress = BitConverter.ToUInt32(IP.GetAddressBytes(), 0);
nRet = SendARP(nAddress, 0, macAddr, ref macAddrLen);
if (nRet == 0)
{
string[] sMacAddress = new string[(int)macAddrLen];
for (int i = 0; i < macAddrLen; i++)
{
sMacAddress[i] = macAddr[i].ToString("x2");
string macAddress += sMacAddress[i] + (i < macAddrLen - 1 ? ":" : "");
}
}
and about speed you can use the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.NetworkInformation;
Start with adding a timerInteval(How fast you want to change to the new value) a NetworkInteface and a timer:
private const double timerUpdate = 1000;
private NetworkInterface[] nicArr;
private Timer timer;
Then Continue using the folowing componets on start up:
public Form1()
{
InitializeComponent();
InitializeNetworkInterface();
InitializeTimer();
}
Componets:
private void InitializeNetworkInterface()
{
// Grab all local interfaces to this computer
nicArr = NetworkInterface.GetAllNetworkInterfaces();
// Add each interface name to the combo box
for (int i = 0; i < nicArr.Length; i++)
comboBox1.Items.Add(nicArr[i].Name); //you add here the interface types in a combobox and select from here WiFi, ethernet etc...
// Change the initial selection to the first interface
comboBox1.SelectedIndex = 0;
}
private void InitializeTimer()
{
timer = new Timer();
timer.Interval = (int)timerUpdate;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
Timer's tick
void timer_Tick(object sender, EventArgs e)
{
UpdateNetworkInterface();
}
With this void you update the ping:
public void UpdatePing()
{
try
{
Ping myPing = new Ping();
PingReply reply = myPing.Send(textBox1.Text, 1000);
if (reply != null)
{
label17.Text = reply.Status.ToString();
label18.Text = reply.RoundtripTime.ToString();
}
}
catch
{
label17.Text = "ERROR: You have Some TIMEOUT issue";
label18.Text = "ERROR: You have Some TIMEOUT issue";
}
}
and finally use this to show the speed in network form:
private void UpdateNetworkInterface()
{
// Grab NetworkInterface object that describes the current interface
NetworkInterface nic = nicArr[comboBox1.SelectedIndex];
// Grab the stats for that interface
IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics();
// Calculate the speed of bytes going in and out
// NOTE: we could use something faster and more reliable than Windows Forms Tiemr
// such as HighPerformanceTimer http://www.m0interactive.com/archives/2006/12/21/high_resolution_timer_in_net_2_0.html
// Update the labels
speedlbl.Text = nic.Speed.ToString();
interfaceTypelbl.Text = nic.NetworkInterfaceType.ToString();
bytesReceivedlbl.Text = interfaceStats.BytesReceived.ToString();
bytesSentlbl.Text = interfaceStats.BytesSent.ToString();
int bytesSentSpeed = (int)(interfaceStats.BytesSent - double.Parse(label10.Text)) / 1024;
int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - double.Parse(label11.Text)) / 1024;
bytescomelbl.Text = bytesSentSpeed.ToString() + " KB/s";
bytessentlbl.Text = bytesReceivedSpeed.ToString() + " KB/s";
}
Win32_NetworkAdapter doesn't support the speed property under XP, As per http://msdn.microsoft.com/en-us/library/windows/desktop/aa394216(v=vs.85).aspx :
Windows Server 2003, Windows XP, Windows 2000, and Windows NT 4.0: This property has not been implemented yet. It returns a NULL value by default.
Instead, use the CIM_NetworkAdapter class with the same property.
http://msdn.microsoft.com/en-us/library/windows/desktop/aa387931(v=vs.85).aspx
using System.Net;
foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces()) {
Debug.WriteLine(netInterface.Name); // Name
Debug.WriteLine(netInterface.Speed); // Speed
Debug.WriteLine(netInterface.GetPhysicalAddress().ToString()); // MAC
}