i need to vibrate the phone while playing a ringtone.
This is my code:
public static bool PlaySound(string soundName)
{
try
{
WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer();
string MediaFile = Assembly.GetExecutingAssembly().GetName().CodeBase.Substring(0, Assembly.GetExecutingAssembly().GetName().CodeBase.LastIndexOf("\\")) + "\\Resources\\" + soundName;
player.URL = MediaFile;
WindowsMediaPlayerClass wmp = new WindowsMediaPlayerClass();
player.settings.volume = 100;
player.controls.play();
SetVibrate(true);
System.Threading.Thread.Sleep((int)wmp.newMedia(MediaFile).duration*1000 + 100);
SetVibrate(false);
return true;
}
catch
{
return false;
}
}
My problem is that the phone FIRST vibrate, then Play sound.. is not possibile to vibrate for the duration of the sound?
thanks.
#x86shadow: I tried with thread but not working :(
public static bool PlaySound(string soundName)
{
try
{
// 29/11/2010 Luca - Aggiungo vibrazione durante il suono del messaggio.
WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer();
string MediaFile = Assembly.GetExecutingAssembly().GetName().CodeBase.Substring(0, Assembly.GetExecutingAssembly().GetName().CodeBase.LastIndexOf("\\")) + "\\Resources\\" + soundName;
player.URL = MediaFile;
WindowsMediaPlayerClass wmp = new WindowsMediaPlayerClass();
player.settings.volume = 100;
RingDuration = (int) wmp.newMedia(MediaFile).duration*1000 + 100;
VibrateWhilePlayingThread = new Thread(VibrateWhilePlaying);
VibrateWhilePlayingThread.Start();
player.controls.play();
VibrateWhilePlayingThread.Join();
return true;
}
catch
{
return false;
}
}
private static int RingDuration;
public static Thread VibrateWhilePlayingThread;
public static void VibrateWhilePlaying()
{
SetVibrate(true);
System.Threading.Thread.Sleep(RingDuration);
SetVibrate(false);
}
Adding an EventHandler:
Player.PlayStateChanged += new AxWMPLib._WMPOCXEvents_PlayChangeEventHandler(player_PlayStateChange);
Try to create an Event:
private void player_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (Player.playState == WMPLib.WMPPlayState.wmppsPlaying)
{
SetVibrate(true);
}
else
{
SetVibrate(false);
}
}
Related
I have just written the C# Code that is recording the screenshot of the desktop.It works on Winforms but not works in windows service.
My code as below:
public partial class ScreenCapture : ServiceBase
{
bool rec = false;
Rectangle screenSize = Screen.PrimaryScreen.Bounds;
UInt32 frameCount = 0;
VideoFileWriter writer;
int width = SystemInformation.VirtualScreen.Width;
int height = SystemInformation.VirtualScreen.Height;
AForge.Video.ScreenCaptureStream streamVideo;
Stopwatch stopWatch = new Stopwatch();
public ScreenCapture()
{
InitializeComponent();
writer = new VideoFileWriter();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource("MySource", "MyLog");
}
eventLog1.Source = "MySource";
this.CanHandleSessionChangeEvent = true;
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
string folderName = #"C:\LoginLog";
if (changeDescription.Reason == SessionChangeReason.SessionLogon)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Logon");
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
StartRec(folderName);
}
else if (changeDescription.Reason == SessionChangeReason.SessionLogoff)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Logoff");
rec = false;
}
else if (changeDescription.Reason == SessionChangeReason.SessionLock)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Lock");
rec = false;
}
else if (changeDescription.Reason == SessionChangeReason.SessionUnlock)
{
eventLog1.WriteEntry(changeDescription.SessionId + " User Unlock");
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
StartRec(folderName);
}
base.OnSessionChange(changeDescription);
}
private void StartRec(string path)
{
if (rec == false)
{
rec = true;
frameCount = 0;
string time = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ssff");
string compName = Environment.UserName;
string fullName = path + "\\" + compName.ToUpper() + "_" + time;
try
{
writer.Open(
fullName + ".mp4",
width,
height,
10,
VideoCodec.MPEG4, 1000000);
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception StartRec: " + ex.Message);
}
DoJob();
}
}
private void DoJob()
{
try
{
Rectangle screenArea = Rectangle.Empty;
foreach (System.Windows.Forms.Screen screen in
System.Windows.Forms.Screen.AllScreens)
{
screenArea = Rectangle.Union(screenArea, screen.Bounds);
}
streamVideo = new ScreenCaptureStream(screenArea);
streamVideo.NewFrame += new NewFrameEventHandler(video_NewFrame);
streamVideo.Start();
stopWatch.Start();
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception DoJob: " + ex.Message);
}
}
private void video_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
try
{
if (rec)
{
frameCount++;
writer.WriteVideoFrame(eventArgs.Frame);
}
else
{
stopWatch.Reset();
Thread.Sleep(500);
streamVideo.SignalToStop();
Thread.Sleep(500);
writer.Close();
}
}
catch (Exception ex)
{
eventLog1.WriteEntry("Exception Video New Frame: " + ex.Message);
}
}
}
And the service can save a .mp4 file, but it cannot open it.I think windows service can not capture desktop screen.
Can anybody help me how to solve this problem?
thanks in advance.
You need to set windows service run under interactive account,
To do so you need to go to properties of service got to logon tab and login by
your windows account.
I need to stream my OS mixer sound to the microphone. (to transfer them both via skype).
Important thing is -- I need to have ability to configure delay/latency of the stream.
(VAC) Virtual Audio Cable is not solution for me: it doesn't work in my case. I have an external USB sound device an app doesn't work for me. I have tried it. Truly.
I google it more than 2 days and found nothing.
So I want to try wrote my own app for this. Have no experience with NAudio.
At the moment all I have is:
using System;
using System.Collections.Generic;
using NAudio.Wave;
namespace SoundApp
{
public class AudioCable
{
private WaveOut _wvOut = null;
private DirectSoundOut _output = null;
private WaveIn _sourceStreamIn = null;
private WaveOut _sourceStreamOut = null;
public void InitDevices(string fromDevice, string toDevice)
{
Dispose();
_sourceStreamIn = new WaveIn();
_sourceStreamOut = new WaveOut();
_output = new DirectSoundOut();
if (fromDevice.Contains("INPUT"))
{
var tmp = fromDevice.Split('|')[0].Replace("INPUT: ", "").Trim(' ');
int tmpDeviceNumber = int.Parse(tmp);
_sourceStreamIn.DeviceNumber = tmpDeviceNumber;
}
else
{
var tmp = toDevice.Split('|')[0].Replace("OUTPUT: ", "").Trim(' ');
int tmpDeviceNumber = int.Parse(tmp);
_sourceStreamOut.DeviceNumber = tmpDeviceNumber;
}
Guid deviceGuid;
if (toDevice.Contains("INPUT"))
{
var tmp = toDevice.Split('|')[0].Replace("INPUT: ", "").Trim(' ');
int tmpDeviceNumber = int.Parse(tmp);
WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(tmpDeviceNumber);
deviceGuid = deviceInfo.ManufacturerGuid;
}
else
{
var tmp = toDevice.Split('|')[0].Replace("OUTPUT: ", "").Trim(' ');
int tmpDeviceNumber = int.Parse(tmp);
WaveOutCapabilities deviceInfo = WaveOut.GetCapabilities(tmpDeviceNumber);
deviceGuid = deviceInfo.ManufacturerGuid;
}
_output = new DirectSoundOut(deviceGuid);
}
public void PlaySound()
{
WaveInProvider waveIn = null;
if (_sourceStreamIn != null)
{
waveIn = new WaveInProvider(_sourceStreamIn);
}
else if (_sourceStreamOut != null)
{
throw new Exception("Sorry, not supported right now");
//waveIn = new WaveInProvider(_sourceStreamOut);
}
_output.Init(waveIn);
_output.Play();
}
public void Dispose()
{
_sourceStreamIn = null;
_sourceStreamOut = null;
if (_output != null)
{
if (_output.PlaybackState == PlaybackState.Playing)
{
_output.Stop();
}
_output.Dispose();
_output = null;
}
}
public string[] GetAudioDevices()
{
var devices = new List<string>();
for (int i = 0; i < WaveIn.DeviceCount; i++)
{
WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(i);
devices.Add($"INPUT: {i} | {deviceInfo.ProductName}");
}
for (int i = 0; i < WaveOut.DeviceCount; i++)
{
WaveOutCapabilities deviceInfo = WaveOut.GetCapabilities(i);
devices.Add($"OUTPUT: {i} | {deviceInfo.ProductName}");
}
return devices.ToArray();
}
}
}
And the form source:
namespace SoundApp
{
public partial class Form1 : Form
{
AudioCable _ac = new AudioCable();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cBoxSource.DropDownStyle = ComboBoxStyle.DropDownList;
cBoxTarget.DropDownStyle = ComboBoxStyle.DropDownList;
cBoxSource.Items.AddRange(_ac.GetAudioDevices());
cBoxTarget.Items.AddRange(_ac.GetAudioDevices());
}
private void btnStartStop_Click(object sender, EventArgs e)
{
_ac.InitDevices(cBoxSource.SelectedItem.ToString(), cBoxTarget.SelectedItem.ToString());
_ac.PlaySound();
}
}
}
So at the first I'm trying to stream microphone to the sound output device.... And it does not work at all.
So My questions is:
There are no microphone sound and I'm do not understand why so. Code is valid and dont throw any errors.
Looks like there is no ability to stream outputDevice sound stream to the inputDevice with NAudio. Is there exist some hack for this?
Specifically, I need to develop a Desktop app that pulls data from H7 Heart Rate Sensor in C# code.
I have searched everywhere and i cant find nothing to help me.
The closest i cam is with this video (https://www.youtube.com/watch?v=Jn05CU3mxzo&list=UUizfLH6Q2igGUyTWO1bH3YA) tutorial but still it didn't find my H7 Heart Rate Sensor.
namespace _123
{
public partial class Form1 : Form
{
List<string> items;
public Form1()
{
InitializeComponent();
items = new List<string>();
}
private void bGo_Click(object sender, EventArgs e)//button
{
if (serverStarted)
{
updateUI("server aleredy started");
return;
}
if (rbClient.Checked) {
startScan();
}
else{
connectAsServer();
}
}
private void startScan() {
listBox1.DataSource = null;
listBox1.Items.Clear();
items.Clear();
Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
bluetoothScanThread.Start();
}
BluetoothDeviceInfo[] devices;
private void scan ()
{
updateUI("Starting scan...");
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevicesInRange();
updateUI("Scan complet");
updateUI(devices.Length.ToString() + "devices discovered");
foreach (BluetoothDeviceInfo d in devices)
{
items.Add(d.DeviceName);
}
updateDeviceList();
}
private void connectAsServer()
{
Thread bluetoothServerTherad = new Thread(new ThreadStart(ServerConnectThread));
bluetoothServerTherad.Start();
}
private void connectAsClient()
{
}
Guid mUUID = new Guid("ECC037FD-72AE-AFC5-9213-CA785B3B5C63");
bool serverStarted = false;
private void ServerConnectThread()
{
//throw new NotImplementedException();
serverStarted = true;
updateUI("Server started, waiting for clients");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mStream = conn.GetStream();
while (true)
{
try
{
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
updateUI("Received: " + Encoding.ASCII.GetString(received));
byte[] sent = Encoding.ASCII.GetBytes("hello world");
mStream.Write(sent, 0, sent.Length);
}
catch (IOException exeption)
{
updateUI("Client has disconected!");
}
}
}
private void updateUI(string message)
{
Func<int> del = delegate()
{
tbOutput.AppendText(message + System.Environment.NewLine);
return 0;
};
Invoke(del);
}
private void updateDeviceList()
{
Func<int> del = delegate()
{
listBox1.DataSource = items;
return 0;
};
Invoke(del);
}
BluetoothDeviceInfo deviceInfo;
private void listBox1_DoubleClick(object sender, EventArgs e)
{
deviceInfo = devices.ElementAt(listBox1.SelectedIndex);
updateUI(deviceInfo.DeviceName + " was selected, attemting connect");
if (pairDevice())
{
updateUI("device paired..");
updateUI("starting conected thread");
Thread bluetoothClientThread = new Thread(new ThreadStart(ClientConnectThread));
bluetoothClientThread.Start();
}
else
{
updateUI("pair failed");
}
}
private void ClientConnectThread()
{
BluetoothClient client = new BluetoothClient();
updateUI("attepting connnection");
client.BeginConnect(deviceInfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
}
void BluetoothClientConnectCallback(IAsyncResult result)
{
BluetoothClient client = (BluetoothClient)result.AsyncState;
client.EndConnect(result);
Stream stream = client.GetStream();
stream.ReadTimeout = 1000;
while (true)
{
while (!ready) ;
stream.Write(message, 0, message.Length);
}
}
string myPin = "1234";
private bool pairDevice()
{
if (!deviceInfo.Authenticated)
{
if (!BluetoothSecurity.PairRequest(deviceInfo.DeviceAddress, myPin))
{
return false;
}
}
return true;
}
bool ready = false;
byte[] message;
private void tbText_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
message = Encoding.ASCII.GetBytes(tbText.Text);
ready = true;
tbText.Clear();
}
}
}
}
This question is old now but here is my answer. So if you have Polar H7 and you are trying to get the Heart rate then I would recommend follow this Bluetooth Low Energy sample and just run the code it should work fine.
After you run this sample click on start enumerating and it will give you list of all the Bluetooth device .
Then find Polar H7 and click on it.
Go to step 2 and hit Connect and choose characteristic and service and you are done.
I have an application that scans the local network for connected PC's.
I want to get the client information (IP address, MAC address, Host name...) and the connection state (download rate, upload rate), and put them in the ListView, but the problem is that this information is not constant!
How could I get this information in real time? The info in the ListView changes every time the info of the client changes?
My current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Text;
using System.Windows.Forms;
using NetUtils;
using System.Net;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
private IPScanner _scanner;
private class HostSorterByIP : IComparer
{
public int Compare(object x, object y)
{
byte[] bytes1 = ((IPScanHostState)((ListViewItem)x).Tag).Address.GetAddressBytes();
byte[] bytes2 = ((IPScanHostState)((ListViewItem)y).Tag).Address.GetAddressBytes();
int i = bytes1.Length - 1;
for (; i > 0 && bytes1[i] == bytes2[i]; i--)
;
return bytes1[i] - bytes2[i];
}
}
public Form1()
{
InitializeComponent();
_scanner = new IPScanner((int)_spnConcurrentPings.Value, (int)_spnPingsPerScan.Value, _cbContinuousScan.Checked,
(int)_spnTimeout.Value, (int)_spnTTL.Value, _cbDontFragment.Checked, (int)_spnBufferSize.Value);
_scanner.OnAliveHostFound += new IPScanner.AliveHostFoundDelegate(_scanner_OnAliveHostFound);
_scanner.OnStartScan += new IPScanner.ScanStateChangeDelegate(_scanner_OnStartScan);
_scanner.OnStopScan += new IPScanner.ScanStateChangeDelegate(_scanner_OnStopScan);
_scanner.OnRestartScan +=new IPScanner.ScanStateChangeDelegate(_scanner_OnRestartScan);
_scanner.OnScanProgressUpdate +=new IPScanner.ScanProgressUpdateDelegate(_scanner_OnScanProgressUpdate);
_lvAliveHosts.ListViewItemSorter = new HostSorterByIP();
_cmbRangeType.SelectedIndex = 0;
}
private void _scanner_OnAliveHostFound(IPScanner scanner, IPScanHostState host)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanner.AliveHostFoundDelegate(_scanner_OnAliveHostFound), scanner, host);
return;
}
ListViewItem item = new ListViewItem();
item.Tag = host;
item.BackColor = Color.GreenYellow;
item.SubItems.Add(host.Address.ToString());
item.SubItems.Add("");
item.SubItems.Add("");
item.SubItems.Add("");
_lvAliveHosts.Items.Add(item);
_lvAliveHosts.Sort();
host.OnHostNameAvailable += new IPScanHostState.HostNameAvailableDelegate(host_OnHostNameAvailable);
host.OnStateChange += new IPScanHostState.StateChangeDelegate(host_OnStateChange);
if (!host.IsTesting())
{
item.ImageIndex = (int)host.QualityCategory;
item.SubItems[2].Text = host.AvgResponseTime.ToString("F02") + " ms";
item.SubItems[3].Text = ((float)(host.LossCount) / host.PingsCount).ToString("P");
item.SubItems[4].Text = host.HostName;
}
//AddLogEntry("Host [" + host.Address.ToString() + "] is alive.");
Timer newTimer = new Timer();
newTimer.Tag = item;
newTimer.Interval = 2000;
newTimer.Tick += new EventHandler(newTimer_Tick);
newTimer.Enabled = true;
}
void host_OnHostNameAvailable(IPScanHostState host)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanHostState.HostNameAvailableDelegate(host_OnHostNameAvailable), host);
return;
}
ListViewItem item = FindListViewItem(host);
if (item != null)
item.SubItems[4].Text = host.HostName;
}
private ListViewItem FindListViewItem(IPScanHostState host)
{
foreach (ListViewItem item in _lvAliveHosts.Items)
{
if (item.Tag == host)
return item;
}
return null;
}
private void host_OnStateChange(IPScanHostState host, IPScanHostState.State oldState)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanHostState.StateChangeDelegate(host_OnStateChange), host, oldState);
return;
}
if (!host.IsTesting())
{
ListViewItem item = FindListViewItem(host);
if (item != null)
{
if (host.IsAlive())
{
item.ImageIndex = (int)host.QualityCategory;
item.SubItems[2].Text = host.AvgResponseTime.ToString("F02") + " ms";
item.SubItems[3].Text = ((float)(host.LossCount) / host.PingsCount).ToString("P");
}
else
{
//AddLogEntry("Host [" + host.Address.ToString() + "] died.");
host.OnStateChange -= host_OnStateChange;
host.OnHostNameAvailable -= host_OnHostNameAvailable;
item.BackColor = Color.IndianRed;
Timer removeTimer = new Timer();
removeTimer.Tag = item;
removeTimer.Interval = 2000;
removeTimer.Tick += new EventHandler(removeTimer_Tick);
removeTimer.Enabled = true;
}
}
}
}
void newTimer_Tick(object sender, EventArgs e)
{
Timer timer = (Timer)sender;
timer.Stop();
timer.Tick -= newTimer_Tick;
ListViewItem item = (ListViewItem)timer.Tag;
item.BackColor = Color.White;
}
void removeTimer_Tick(object sender, EventArgs e)
{
Timer timer = (Timer)sender;
timer.Stop();
timer.Tick -= newTimer_Tick;
ListViewItem item = (ListViewItem)timer.Tag;
_lvAliveHosts.Items.Remove(item);
}
private void _scanner_OnStartScan(IPScanner scanner)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanner.ScanStateChangeDelegate(_scanner_OnStartScan), scanner);
return;
}
foreach (ListViewItem item in _lvAliveHosts.Items)
{
((IPScanHostState)item.Tag).OnStateChange -= host_OnStateChange;
((IPScanHostState)item.Tag).OnHostNameAvailable -= host_OnHostNameAvailable;
}
_lvAliveHosts.Items.Clear();
_prgScanProgress.Value = 0;
EnableSettings(false);
}
private void EnableSettings(bool enable)
{
_cmbRangeType.Enabled = _tbRangeStart.Enabled = _tbRangeEnd.Enabled = _spnTimeout.Enabled = _spnTTL.Enabled = _spnBufferSize.Enabled = _cbDontFragment.Enabled =
_spnConcurrentPings.Enabled = _spnPingsPerScan.Enabled = _cbContinuousScan.Enabled = enable;
_btnStartStop.Text = enable ? "&Start" : "&Stop";
if (enable)
_prgScanProgress.Text = "Scanner is not running!";
}
private void _btnStartStop_Click(object sender, EventArgs e)
{
if (!_scanner.Active)
{
try
{
_scanner.Start(_cmbRangeType.SelectedIndex == 0
? new IPScanRange(IPAddress.Parse(_tbRangeStart.Text), IPAddress.Parse(_tbRangeEnd.Text))
: new IPScanRange(IPAddress.Parse(_tbRangeStart.Text), int.Parse(_tbRangeEnd.Text)));
}
catch (FormatException)
{
MessageBox.Show(this, "Cannot parse IP range or subnetmask!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
_scanner.Stop(false);
}
private void _scanner_OnStopScan(IPScanner scanner)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanner.ScanStateChangeDelegate(_scanner_OnStopScan), scanner);
return;
}
EnableSettings(true);
_prgScanProgress.Value = 0;
}
void _scanner_OnRestartScan(IPScanner scanner)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanner.ScanStateChangeDelegate(_scanner_OnRestartScan), scanner);
return;
}
_prgScanProgress.Value = 0;
}
void _scanner_OnScanProgressUpdate(IPScanner scanner, IPAddress currentAddress, ulong progress, ulong total)
{
if (InvokeRequired)
{
BeginInvoke(new IPScanner.ScanProgressUpdateDelegate(_scanner_OnScanProgressUpdate), scanner, currentAddress, progress, total);
return;
}
int prog = (int)((100 * progress) / total);
_prgScanProgress.Value = prog;
_prgScanProgress.Text = prog.ToString() + "%" + " [" + currentAddress.ToString() + "]";
}
private void _cmbRangeType_SelectedIndexChanged(object sender, EventArgs e)
{
if (_cmbRangeType.SelectedIndex == 0)
{
_lRangeSep.Text = "-";
_lRangeEnd.Text = "Range &End:";
_tbRangeEnd.Size = new Size(130, _tbRangeEnd.Size.Height);
}
else
{
_lRangeSep.Text = "/";
_lRangeEnd.Text = "Subnet &Mask:";
_tbRangeEnd.Size = new Size(32, _tbRangeEnd.Size.Height);
}
}
//private void _lvAliveHosts_DoubleClick(object sender, EventArgs e) { _btnAddHost_Click(sender, e); }
private void IPScanForm_FormClosing(object sender, FormClosingEventArgs e) { _scanner.Stop(true); }
private ListViewItem.ListViewSubItem _activeTooltipSubitem = null;
private static string[] QualityCategoryNames = { "Very Poor", "Poor", "Fair", "Good", "Very Good", "Excellent", "Perfect" };
private void _lvAliveHosts_MouseMove(object sender, MouseEventArgs e)
{
ListViewItem item = _lvAliveHosts.HitTest(e.Location).Item;
if (item != null)
{
ListViewItem.ListViewSubItem subitem = _lvAliveHosts.HitTest(e.Location).SubItem;
if (subitem != null && item.SubItems.IndexOf(subitem) == 0)
{
if (_activeTooltipSubitem != subitem)
{
_ttQuality.Show("Quality: " + QualityCategoryNames[item.ImageIndex], _lvAliveHosts, item.SubItems[1].Bounds.X, subitem.Bounds.Y);
_activeTooltipSubitem = subitem;
}
return;
}
}
_activeTooltipSubitem = null;
_ttQuality.Hide(_lvAliveHosts);
}
}
}
I would create the list of clients and show them in the listview.
Than, in a background thread, every X seconds, poll all of the current clients.
Next , compare the list of updated clients to a list of clients from last update.
What remain to do is to add any new client to the list, and remove any client which no longer exists.
Pay attention to the context, use InvokeRequired() to get access to the UI control from the background thread.
EDIT:
here is how to run a background thread:
static void Main(string[] args)
{
Thread worker = new Thread(DoBackgroundWork);
}
public static void DoBackgroundWork()
{
while (true)
{
//Sleep 10 seconds
Thread.Sleep(10000);
//Do some work and than post to the control using Invoke()
}
}
I want my application will show on my form my class properties so I started my class with BackgroundWorker and create ProgressChanged.
my class:
public class DumpFile
{
PacketDevice _device;
public int _packetsCount;
public double _bitsPerSecond;
public double _packetsPerSecond;
public DateTime _lastTimestamp;
public delegate void dlgPackProgress(int progress);
public event dlgPackProgress evePacketProgress;
public DumpFile(PacketDevice device, string pcapPath)
{
_device = device;
_pcapPath = pcapPath;
_packetsCount = 1;
}
public void startCapturing()
{
OnPacketProgress(_packetsCount++);
using (PacketCommunicator communicator = _device.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000)) //open the device
{
ThreadStart starter = delegate { openAdapterForStatistics(_device); };
new Thread(starter).Start();
using (PacketDumpFile dumpFile = communicator.OpenDump(_pcapPath)) //open the dump file
{
communicator.ReceivePackets(0, dumpFile.Dump); //start the capture
}
}
}
private void OnPacketProgress(int packet)
{
var handler = evePacketProgress;
if (handler != null)
{
handler(packet);
}
}
public void openAdapterForStatistics(PacketDevice selectedOutputDevice)
{
using (PacketCommunicator statCommunicator = selectedOutputDevice.Open(100, PacketDeviceOpenAttributes.Promiscuous, 1000)) //open the output adapter
{
ThreadStart start = delegate { test(selectedOutputDevice); };
new Thread(start).Start();
statCommunicator.SetFilter("tcp"); //compile and set the filter
statCommunicator.Mode = PacketCommunicatorMode.Statistics; //put the interface in statstics mode
statCommunicator.ReceiveStatistics(0, StatisticsHandler);
}
}
public void test(PacketDevice selectedOutputDevice)
{
using (PacketCommunicator communicator = selectedOutputDevice.Open(65536, PacketDeviceOpenAttributes.Promiscuous, 1000))
{
communicator.ReceivePackets(0, PacketHandler);
}
}
private void PacketHandler(Packet packet)
{
string result = _packetsCount.ToString() + ". " + packet.Timestamp.ToString("yyyy-MM-dd hh:mm:ss.fff") + " length:" + packet.Length;
_packetsCount++;
}
private void StatisticsHandler(PacketSampleStatistics statistics)
{
DateTime currentTimestamp = statistics.Timestamp; //current sample time
DateTime previousTimestamp = _lastTimestamp; //previous sample time
_lastTimestamp = currentTimestamp; //set _lastTimestamp for the next iteration
if (previousTimestamp == DateTime.MinValue) //if there wasn't a previous sample than skip this iteration (it's the first iteration)
{
return;
}
double delayInSeconds = (currentTimestamp - previousTimestamp).TotalSeconds; //calculate the delay from the last sample
_bitsPerSecond = statistics.AcceptedBytes * 8 / delayInSeconds; //calculate bits per second
_packetsPerSecond = statistics.AcceptedPackets / delayInSeconds; //calculate packets per second
}
}
start button who start capturing:
private void btnStartCapture_Click(object sender, EventArgs e)
{
timerSniffer.Start();
btnStartTabSniffer.Enabled = false;
btnStopTabSniffer.Enabled = true;
groupBoxSelectTabSniffer.Enabled = false;
bgWorker = new BackgroundWorker();
bgWorker.WorkerReportsProgress = true;
bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWSniffer_ProgressChanged);
bgWorker.DoWork += new DoWorkEventHandler(
(s3, e3) =>
{
DumpFile dumpFile = new DumpFile(deviceForCapturing, pcapFilePathSniffer);
tshark.evePacketProgress += new DumpFile.dlgPackProgress(
(packet) =>
{
bgWorker.ReportProgress(packet, dumpFile);
});
dumpFile.startCapturing();
});
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(s3, e3) =>
{
groupBoxSelectTabSniffer.Enabled = true;
});
bgWorker.RunWorkerAsync();
}
ProgressChanged:
private void bgWSniffer_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var dumpFile = (DumpFile)e.UserState;
lblNumberOfPacketsTabSniffer2.Text = dumpFile._packetsCount.ToString("#,##0");
lblTrafficRateTabSniffer2.Text = (dumpFile._bitsPerSecond * 0.000001).ToString("0.##") + " Mbit/sec" + " (" + dumpFile._bitsPerSecond.ToString("#,##0") + " Bits/sec" + ")";
lblPacketsRateTabSniffer2.Text = dumpFile._packetsPerSecond.ToString("#,##0") + " Packets/sec";
}
the problem is that my application "get into" ProgressChanged functions but only in one time.
I think I missed something in my class.
I can only find one call to OnPacketProgress(), and it's outside of any loop.
public void startCapturing()
{
OnPacketProgress(_packetsCount++);
....
}
So Yes, that will only be called once.
You need something inside ReceivePackets()