C# WPF capture image on external USB Camera button - usb

I have a USB Camera, MotuhWatch you can see it here
The device has a button on it to capture an Image.
I'm working on a C# WPF application to show and save the captured image.
I'm successful to catch the event when the device connects with the laptop or PC.
But facing in capturing the event when the CAPTURE button the camera is pressed.
I searched a lot and studied many solutions but got no success.
The below link help me a lot but I got no success, might be I'm making a mistake.
Solution 1
Solution 2
Solution 3
Here is my code to catch the Event when the USB Camera connects,
public MainWindow()
{
InitializeComponent();
ManagementEventWatcher watcher = new ManagementEventWatcher();
WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Query = query;
watcher.Start();
}
private void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
MessageBox.Show("USB Dental Camera Connected Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Exception Occur: " + ex.Message);
}
}
I am open to suggestions :)

Related

Replicate Hardware Back Button Functionality from UI in Windows Phone

I'm trying to write a windows phone application and am wondering if it's possible to have a software button in the UI that does the same thing as the hardware back button (just sends a system back command). I can't seem to find any information on how to do this online.
try this:
XAML:
<Button x:Name="btnBack" Content="Back" Click="btnBack_Click"></Button>
CS:
private void btnBack_Click(object sender, RoutedEventArgs e)
{
if (NavigationService.CanGoBack)
NavigationService.GoBack();
else
App.Current.Terminate();
}
This would work as same Back button. if any back-state is there it would go to that state or if not it would close (Terminate) the Application.
you can override the back button function
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
//Do your work here
base.OnBackKeyPress(e);
}

Message Dialog not displaying on Windows 8 tablet - Caliburn.Micro/C#

Has anyone heard of any issues with MessageDialog's not displaying on Windows 8 tablets? Or more specifically Samsung 700t? It uses a regular intel process and not ARM. I built the app on a laptop and the messagedialog shows when debugging from the laptop, shows on the tablet simulator but doesn't show on the actual tablet.
I'm using the Caliburn.Micro IResult interface to display the messagedialog in the view.
Heres snippits of code that I'm using:
public IEnumerable<IResult> NavExecute(String method)
{
Windows.UI.ViewManagement.ApplicationView.TryUnsnap();
var conn = NetworkInformation.GetInternetConnectionProfile();
if (conn.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.InternetAccess)
{
yield return new MessageDialogResult("Internet Connection Not Detected", "Connection Error");
netOn = false;
}
}
the above is in my view model base class, and heres the implementation of the IResult class itself:
public class MessageDialogResult : ResultBase
{
private readonly string _content;
private readonly string _title;
public MessageDialogResult(string content, string title)
{
_content = content;
_title = title;
}
public async override void Execute(ActionExecutionContext context)
{
var dialog = new MessageDialog(_content, _title);
await dialog.ShowAsync();
OnCompleted();
}
}
I doub't it's an issue with the code since I'm debugging in x86 mode on both devices (before anyone asks why I'm not debugging for all devices it's because I'm using SQLite which requires a seperate package for each arhitecture.)
I'm not sure if theres a setting somewhere in Windows 8 that disables in app popups, but I couldn't find one.
Any ideas?
Are you handling the callback of Coroutine.Execute?
The callback on Execute might be calling back with an exception thrown by the coroutine - this would silently fail if you weren't explicitly looking for it in the callback
Coroutine.Execute(YourEnumerator(), new ActionExecutionContext { Blah }, (o, e) => {
if(e.Error != null) // Something went wrong
});
Maybe the async await is throwing or something like that (can't think why!)
Edit:
Ah additionally stuff in your enumerator could also throw:
Windows.UI.ViewManagement.ApplicationView.TryUnsnap();
var conn = NetworkInformation.GetInternetConnectionProfile();
Either one could throw making the outer enumerator swallow an exception if not handled in the callback - or could be a nullref on conn?
The reason why GetInternetConnectionProfile() was returning a null ref was due to the fact that when on a laptop, if you disconnect from a wireless connection the laptop's internet connection profile defaults to ethernet, whereas the tablet (at least the Samsung 700T) doesn't have an ethernet port so it's connection profile doesn't exist if a wireless connection isn't established.
Thanks to Charleh for pointing me in the right direction.

Unable to play sound in Windows 8

I want to play sound from a mp3 file in windows 8 metro-style app. I tried two approaches to do so:
Method1:
This is using the code provided by https://stackoverflow.com/a/10961201/147530. It works.
Method 2:
Here I just new a MediaElement and set its Source property like so:
var x = new MediaElement { Source = new Uri("ms-appx:/Assets/MyMp3File.mp3") };
When I do x.Play() nothing happens however. There are no exceptions thrown.
Question: How can I make method 2 work?
EDIT:
Wanted to update that none of the MediaFailed, MediaOpened, MediaEnded event handlers get called using Method 2.
sound = new MediaElement { Source = new Uri("ms-appx:/Assets/Clook.mp3") };
sound.MediaFailed += sound_MediaFailed;
sound.MediaOpened += sound_MediaOpened;
sound.MediaEnded += sound_MediaEnded;
static void sound_MediaEnded(object sender, RoutedEventArgs e)
{
Debugger.Break();
}
static void sound_MediaOpened(object sender, RoutedEventArgs e)
{
Debugger.Break();
}
static void sound_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
Debugger.Break();
}
A couple of things to try. Try the following code
var music = new MediaElement()
{
AudioCategory = AudioCategory.ForegroundOnlyMedia,
Source = new Uri(this.BaseUri, "Assets/MyMp3File.mp3")
};
// This is really the only difference, adding it to the visual tree
// LayoutRoot is the root of the visual tree, in the case, a grid in my XAML
LayoutRoot.Children.Add(music);
music.Play();
Adding it to the visual tree may be the key. Put a break point on that to make sure your MediaElement has data in it.
Second (and actually happened to me so, that's why I mention it), I was developing on a Samsung device from //Build that has a docking station. The audio jack on the device and the speakers are disabled when it is in the docking station. You have to plug a headset into the docking station directly or remove it from the docking station to hear any sound.
You have to put the MediaElement in the visualTree before to make it play any media :)
Use x.autoplay = true. With autoplay it will wait until it's loaded.

Wakelock only working with usb-cable connected

I have a rather odd problem. Lately i tried to use a wakelock in my application using the following code:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
screenLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
System.out.println("Clicked");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!locked)
setKeepScreenOn(WakeupLightActivity.this, true);
else setKeepScreenOn(WakeupLightActivity.this, false);
System.out.println("Screen will stay on");
}
});
}
public void setKeepScreenOn(Activity activity, boolean keepScreenOn) {
if(keepScreenOn) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.screenLock.acquire();
}
else {
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
this.screenLock.release();
}
}
The wakelock works perfectly: 5 seconds after pressing the button (and locking my phone) the screen turns on. This test, however, was done while my phone was connected to my laptop for debugging using a USB cable.
Now comes the weird part. When I DON'T have my phone connected with the USB cable, the wakelock simply DOES NOT turn on the screen. The device I am using is an HTC desire. I have actually tested it on another HTC desire, which did the same thing. Next, i tried it on an HTC Desire HD. And guess what: It worked perfectly again! I am really confused about this and wondering if the problem is simply a flaw in my phone type, or if I am doing something wrong in my code. Is there anything I can do about it? It would be incredibly awkward if any potential customers with a malfunctioning phone type would encounter the same problem after having purchased my app.
Note that I also tried the application while charging my phone with the cable connected to a wall plug. This leads to the same problem as not having my phone connected at all. Both HTC Desires run the same Android version (2.2.2).
Apparently all of this occured simply because i was using the wrong flags. The problem was solved by creating the WakeLock with the following flags:
PowerManager.SCREEN_BRIGHT_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP

Application crashes when lots of images are displayed

In my WP7 application I have downloaded 200 images from Web and saved in isolated storage .When debug all the images are loaded in panorama view by queue method and I can view when it is connected to pc. after disconnect it from pc when i open the application and navigate the images it shows some images and terminated.
if (i < 150)
{
WebClient m_webClient = new WebClient();
Uri m_uri = new Uri("http://d1mu9ule1cy7bp.cloudfront.net/2012//pages/p_" + i + "/mobile_high.jpg");
m_webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
m_webClient.OpenReadAsync(m_uri);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
int count;
try
{
Stream stream = e.Result;
byte[] buffer = new byte[1024];
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
//isf.Remove();
using (System.IO.IsolatedStorage.IsolatedStorageFileStream isfs = new IsolatedStorageFileStream("IMAGES" + loop2(k) + ".jpg", FileMode.Create, isf))
{
count = 0;
while (0 < (count = stream.Read(buffer, 0, buffer.Length)))
{
isfs.Write(buffer, 0, count);
}
stream.Close();
isfs.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I think that your problem is that if you load too many images at once in a loop the moment you go out of the loop and give focus back to the UI thread all the Garbage Collection on the bitmap images is done.
This article explains it a bit better and provides with a solution.
I also had this problem and came up with my own solution. I had a dictonairy with image url that needed to be loaded, but you can easily alter this for your scenario.
This SO question is also about this problem (loading multiple images and crash (Exception)). It also has Microsofts response to it, I based my solution on their response.
In my solution I use the dispatcher to return to the UI thread and thus making sure the garbage of the image and bitmaps used was cleaned.
private void LoadImages(List<string> sources)
{
List<string>.Enumerator iterator = sources.GetEnumerator();
this.Dispatcher.BeginInvoke(() => { LoadImage(iterator); });
}
private void LoadImage(List<string>.Enumerator iterator)
{
if (iterator.MoveNext())
{
//TODO: Load the image from iterator.Current
//Now load the next image
this.Dispatcher.BeginInvoke(() => { LoadImage(iterator); });
}
else
{
//Done loading images
}
}
After talking on Skype I reviewed his code and found out his problem was with his Isolated Storage Explorer. It couldnt connect to his pc so it gave an error. Had nothing to do with the image loading.
I'd be very wary of the memory implications of loading 200 images at once. Have you been profiling the memory usage? Using too much memory could cause your application to be terminated.