Open Windows Form with opcv From wpf windows - c#

note I am new in Wpf >
I have project that decode qr code by using opencv library throw web cam >
and it running successfully
now I wanna to using this project in new Wpf project >
after adding new wpf project and make reference to WinForms application >
and this my simple code to open WinForm >
public void runnow(){
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new CameraCapture.cameraCapture()); }
by ruining give me this exception >
The type initializer for 'Emgu.CV.CvInvoke' threw an exception.>
what can I do for solve this
C# code
public partial class CameraCapture : Form
{
Capture capture;
bool Capturing;
Bitmap bimap;
private Reader reader;
private Hashtable hint;
libAES libEncryption = new libAES();
string Mykey = "";
public static String dataDecrypted="";
public CameraCapture()
{
InitializeComponent();
}
private void Mains(object sender, EventArgs arg) // Start function main to encode Qr code
{
Image<Bgr, Byte> image = capture.QueryFrame();
if (image != null)
{
bimap = image.ToBitmap();
pictureBox1.Image = bimap;
reader = new QRCodeReader();
hint = new Hashtable(); // Add some elements to the hash table. There are no duplicate keys, but some of the values are duplicates.
hint.Add(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
RGBLuminanceSource source = new RGBLuminanceSource(bimap, bimap.Width, bimap.Height); //This class is used to help decode images from files which arrive as RGB data from* Android bitmaps. It does not support cropping or rotation.
BinaryBitmap img = new BinaryBitmap(new GlobalHistogramBinarizer(source));
Result result = null;
try
{
result = reader.decode(img, hint);
dataDecrypted = libEncryption.Decrypt(result.Text, Mykey);
}
catch
{
dataDecrypted = "";
}
if (result == null)
{
label1.Text = " no decode";
}
else
{
label4.Text = result.Text;
label1.Text = dataDecrypted;
capture.Dispose();
}
}
} // end function Main
private void btnStart_Click(object sender, EventArgs e)
{
if (capture == null)
{
try
{
capture = new Capture(); // **the exption thown here**
}
catch (NullReferenceException exception)
{
MessageBox.Show(exception.Message);
}
}
if (capture != null)
{
if (Capturing)
{
btnStart.Text = "Start Capture";
Application.Idle -= Mains;
}
else
{
btnStart.Text = "Stop Capture";
Application.Idle += Mains;
}
Capturing = !Capturing;
}
}
private void Release()
{
if (capture != null)
capture.Dispose();
}}

If you want to host WinForm in WPF, you need to use host control System.Windows.Forms.Integration.WindowsFormsHost
WPF provides many controls with a rich feature set. However, you may
sometimes want to use Windows Forms controls on your WPF pages. For
example, you may have a substantial investment in existing Windows
Forms controls, or you may have a Windows Forms control that provides
unique functionality.
Example code
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Create the interop host control.
System.Windows.Forms.Integration.WindowsFormsHost host =
new System.Windows.Forms.Integration.WindowsFormsHost();
// Create the MaskedTextBox control.
MaskedTextBox mtbDate = new MaskedTextBox("00/00/0000");
// Assign the MaskedTextBox control as the host control's child.
host.Child = mtbDate;
// Add the interop host control to the Grid
// control's collection of child controls.
this.grid1.Children.Add(host);
}
Check =>
http://msdn.microsoft.com/en-us/library/ms751761.aspx

Related

How can I load multiple images using LoadAsync() in C#?

I'm trying to update the GUI, and I have an asynchronous function that uses LoadAsyc(), when I load just one image, it works but when I try to load more than one, the second one doesn't display.
This my code:
public UserFriendlyInterface()
{
InitializeComponent();
locationFileH5 = "";
serverStatus = false;
ipAddress = getLocalIPAddress();
port = 5000;
watcher = new FileSystemWatcher(#"flask_server\cnn\_prepImages_");
watcher.EnableRaisingEvents = true;
watcher.Changed += watcher_Changed;
}
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
updateImages();
}
async Task updateImages()
{
pictureBoxNormalImg.WaitOnLoad = false;
pictureBoxNormalImg.LoadAsync(#"flask_server\cnn\_prepImages_\normal.jpg");
pictureBoxSegmentation.WaitOnLoad = false;
pictureBoxSegmentation.LoadAsync(#"flask_server\cnn\_prepImages_\segmentation.jpg");
}
What you are trying to achieve can be achieved more robustly by querying the Name property of the FileSystemEventArgs object, and updating only the corresponding PictureBox.
private static void Watcher_Changed(object sender, FileSystemEventArgs e)
{
PictureBox pictureBox;
switch (e.Name.ToLowerInvariant())
{
case "normal.jpg": pictureBox = pictureBoxNormalImg; break;
case "segmentation.jpg": pictureBox = pictureBoxSegmentation; break;
default: pictureBox = null; break;
}
if (pictureBox != null)
{
Image image = null;
try
{
using (var temp = new Bitmap(e.FullPath))
{
image = new Bitmap(temp);
}
}
catch { } // Swallow exception
if (image != null)
{
pictureBox.Invoke((MethodInvoker)(delegate ()
{
pictureBox.Image = image;
}));
}
}
}
I would avoid the LoadAsync method because it is intended mainly for loading images from the internet, and because I don't totally trust it.
Update: There were two problems with my initial code:
1) Free file locked by new Bitmap(filePath)
2) FileSystemWatcher Changed event is raised twice
The updated code solves these problems (hopefully), but not in the most robust or efficient way possible.
Update: To make the code more efficient, by avoiding the repeated loading of the images caused by multiple firings of the Changed event, you could use the extension method OnChanged found in this answer. It suffices to replace the line below:
watcher.Changed += Watcher_Changed;
...with this one:
watcher.OnChanged(Watcher_Changed, 100);

How to access the camera from my Windows Phone 8 app (XAML and C#) and save the taken picture in a determined folder?

I want the Windows Phone 8 app that I am building at this moment to access the camera for taking a photo when a concrete button on the screen is pressed and then save the image that has been taken into a determined folfer (a folder created into the Windows Phone project by me, not the Windows Phone default image gallery).
Could you help me accesing the camera, taking the picture and saving it into the folder created by me, please? I am using XAML and C#.
Thank you so much!!!
I would recommend PhotoCamera class if capture is to be processed on a button in the app
PhotoCamera myCamera = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
//viewfinderBrush is a videobrush object declared in xaml
viewfinderBrush.SetSource(myCamera);
myCamera.Initialized += myCamera_Initialized;
myCamera.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted);
myCamera.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(camera_CaptureImageAvailable);
//Events
void myCamera_Initialized(object sender, CameraOperationCompletedEventArgs e)
{
try
{
if (e.Succeeded)
{
}
}
catch
{
MessageBox.Show("Problem occured in camera initialization.");
}
}
void camera_CaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
{
try
{
}
catch
{
MessageBox.Show("Captured image is not available, please try again.");
}
}
void camera_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
try
{
}
catch (Exception ex)
{
MessageBox.Show("Captured image is not available, please try again. " + ex.Message);
}
}
And there is one more alternative called CameraCaptureTask
CameraCaptureTask cameraCaptureTask;
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
cameraCaptureTask.Show();
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
//System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
//bmp.SetSource(e.ChosenPhoto);
//myImage.Source = bmp;
}
}
Check this for PhotoCamera class
And this for CameraCaptureTask
There's a simple code demonstration here showing your to put the camera API to use for Windows Phone8 apps.
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
(PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true)) {
// Initialize the default camera.
_photoCamera = new Microsoft.Devices.PhotoCamera();
//Event is fired when the PhotoCamera object has been initialized
_photoCamera.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(OnPhotoCameraInitialized);
//Set the VideoBrush source to the camera
viewfinderBrush.SetSource(_photoCamera);
}
else {
// The camera is not supported on the device.
this.Dispatcher.BeginInvoke(delegate() {
// Write message.
txtDebug.Text = "A Camera is not available on this device.";
});
}
}
private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e) {
int width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
int height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);
}
Dont forget to add this line in WMAppManifent.xml file.
<Capability Name="ID_CAP_ISV_CAMERA"/>
you can read here ,
Using Cameras in Your Windows Phone Application

How to print Webview on a windows store app

Hey guys i have been trying to print my Webview using the tutorial Jerry Nixon gave on How do I print WebView content in a Windows Store App? and the tutorial from "windows 8 apps with xaml and c#" by Adam Nathan, i have attached the code below from his example:
using System;
using Windows.Graphics.Printing;
using Windows.Graphics.Printing.OptionDetails;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Printing;
namespace Chapter19
{
public sealed partial class MainPage : Page
{
// Supports printing pages, where each page is a UIElement
PrintDocument doc = new PrintDocument();
public MainPage()
{
InitializeComponent();
// Attach handlers to relevant events
doc.GetPreviewPage += OnGetPreviewPage;
doc.AddPages += OnAddPages;
PrintManager printManager = PrintManager.GetForCurrentView();
printManager.PrintTaskRequested += OnPrintTaskRequested;
}
// Prepare the print preview pages
void OnGetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
this.doc.SetPreviewPageCount(2, PreviewPageCountType.Final);
if (e.PageNumber == 1)
{
this.doc.SetPreviewPage(1, new Viewbox
{
Child = new Button
{
Content = "PAGE 1!",
Background = new SolidColorBrush(Colors.Red)
}
});
}
else
{
this.doc.SetPreviewPage(2, new Viewbox
{
Child = new Button
{
Content = "PAGE 2!",
Background = new SolidColorBrush(Colors.Red)
}
});
}
}
// Prepare the real pages
void OnAddPages(object sender, AddPagesEventArgs e)
{
this.doc.AddPage(new Viewbox
{
Child = new Button
{
Content = "PAGE 1!",
Background = new SolidColorBrush(Colors.Red)
}
});
this.doc.AddPage(new Viewbox
{
Child = new Button
{
Content = "PAGE 2!",
Background = new SolidColorBrush(Colors.Red)
}
});
this.doc.AddPagesComplete();
}
// Prepare and perform the printing
void OnPrintTaskRequested(PrintManager sender,
PrintTaskRequestedEventArgs args)
{
// This gets invoked as soon as the Devices pane is shown
PrintTask task = args.Request.CreatePrintTask("Document Title",
async (taskArgs) =>
{
// This is invoked on a background thread when the Print
// button is clicked
var deferral = taskArgs.GetDeferral();
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// This must run on the main thread
taskArgs.SetSource(doc.DocumentSource);
deferral.Complete();
});
});
// Show custom options
PrintTaskOptionDetails details =
PrintTaskOptionDetails.GetFromPrintTaskOptions(task.Options);
details.DisplayedOptions.Clear();
details.DisplayedOptions.Add(StandardPrintTaskOptions.MediaSize);
// A custom text option
PrintCustomTextOptionDetails option1 = details.CreateTextOption(
"CustomId1", "Header");
details.DisplayedOptions.Add("CustomId1");
// A custom list option
PrintCustomItemListOptionDetails option2 = details.CreateItemListOption(
"CustomId2", "Contents");
option2.AddItem("customItemId1", "As Seen on Screen");
option2.AddItem("customItemId2", "Summary View");
option2.AddItem("customItemId3", "Full Details");
option2.AddItem("customItemId4", "Multiple Columns");
details.DisplayedOptions.Add("CustomId2");
// Handle options changes
details.OptionChanged += OnOptionChanged;
}
void OnOptionChanged(PrintTaskOptionDetails sender, PrintTaskOptionChangedEventArgs args)
{
// TODO: Handle custom options
}
}
}
the problem i am having is that i am struggling to get "MywebviewPages" that jerry generated onto the
"this.doc.SetPreviewPage"
and
"this.doc.AddPage"
from Nathans example. Due to lack of PDF api's on winRT i am forced to use webview since its the only way to have tables. please help

Capture class (Emgu) issue in multiple background worker threads

I have a simple Winforms app that allows users to select multiple videos (files) simultaneously and runs background workers threads to loop through each of the videos in the BW. Have pasted code below, I get a NullReferenceException as "Unable to create capture from ..." at this line
Capture _capture = new Capture(videoFileName)
in processVideo method.
N.B: The same code work fine if I select a single video. So some issue with the multiple instances of Capture class.
I would expect the ProcessVideo method to have new instance of Capture and open it separately. Any ideas on what I might be doing wrong?
private void openVideoToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Video | *.AVI;*.MPEG;*.WMV;*.MP4;*.MOV;*.MPG;*.MPEG;*.MTS;*.FLV";
ofd.Multiselect = true;
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] videos = ofd.FileNames;
if (videos != null)
{
BackgroundWorker[] bw = new BackgroundWorker[videos.GetLength(0)];
int n = 0;
foreach (string video in videos)
{
bw[n] = new BackgroundWorker();
bw[n].DoWork += new DoWorkEventHandler(bw_DoWork);
bw[n++].RunWorkerAsync(video);
}
}
}
}
catch (NullReferenceException excpt)
{
MessageBox.Show(excpt.Message);
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
string filename = (string)e.Argument;
ProcessVideo(filename);
}
private void ProcessVideo(string videoFileName)
{
Capture _capture = new Capture(videoFileName);
UInt64 TOTAL_FRAMES = Convert.ToUInt64(_capture.GetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_COUNT));
for (UInt64 n = 0; n < TOTAL_FRAMES; n++)
{
using (Image<Bgr, Byte> img1 = _capture.QueryFrame())
{
//do something with the frame
}
}
}
I suggest you to update Sourcesafe service pack
it may help you
[I think you code is perfect there is
nothing wrong in it.
You got an error while creating object it clearly saw that
there may be chance that file format is not supported
or may be internal error problem.]
Let me know that after doing updation it works or not.
Regards Red

How to click on multiple links on multiple pages in webBrowser

Iam Unable to do this from past one week. I want to click on multiple links n multiple web pages using webBrowser in C# Following is the code please help me in this regard.
public void DoDelete()
{
int count = 0;
if (corruptList.Count > 0)
{
foreach (string listItem in corruptList)
{
var th = new Thread(() =>
{
try
{
WebBrowser webBrowser = new WebBrowser();
webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBroswer_DocumentCompleted);
webBrowser.Navigate(listItem);
Thread.Sleep(100);
webBrowser.Dispose();
}
catch (Exception ex)
{
throw ex;
}
this.Invoke(new MethodInvoker(delegate
{
dataGridView_CorruptLinks.Rows[count].Cells[2].Value = "Deleted";
}));
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
Thread.Sleep(100);
}
count++;
}
}
void webBroswer_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
WebBrowser webBrowser = sender as WebBrowser;
HtmlElementCollection ec = webBrowser.Document.GetElementsByTagName("a");
foreach (HtmlElement item in ec)
{
if (item.InnerHtml == "Delete this invalid field")
{
item.InvokeMember("Click");
break;
}
}
}
catch (Exception exp)
{
}
}
Navigate is an asynchronous action and you're only giving it 1/10 of a second to complete before you call Dispose on the web browser object. Your navigation and clicks are probably taking longer than that to complete and so there is no web browser to act against... You're also "swallowing" all exceptions in the document complete handler. This is a very bad thing to do. You should at the very least be doing some debug logging there to help yourself diagnose the problem.
But, to keep the similar logic you should create a collection of web browsers at class level. Something like:
private List<WebBrowser> _myWebBrowsers;
Then add to this list in your loop but do not call Dispose. You should only dispose of the browser when you're done with it.
That should get you closer though there are a few other potential issues with your code. You're allocating a borser object and thread for every time through a loop. This could quickly become unwieldy. You should use a thread management mechanism to throttle this process.
Simplified class:
class WebRunner
{
private List<string> _corruptList = new List<string>();
private List<WebBrowser> _browsers = new List<WebBrowser>();
public void Run()
{
_corruptList.Add("http://google.com");
_corruptList.Add("http://yahoo.com");
_corruptList.Add("http://bing.com");
DoDelete();
Console.ReadKey();
}
public void DoDelete()
{
if (_corruptList.Count < 1) return;
int counter = 1;
foreach (string listItem in _corruptList)
{
WebBrowser webBrowser = new WebBrowser();
_browsers.Add(webBrowser);
webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBroswer_DocumentCompleted);
webBrowser.Navigated += new WebBrowserNavigatedEventHandler(webBrowser_Navigated);
webBrowser.Navigate(listItem);
if (counter % 10 == 0) Thread.Sleep(3000); // let app catch up every so often
counter++;
}
}
void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
Console.WriteLine("NAVIGATED: " + e.Url);
}
void webBroswer_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
Console.WriteLine("COMPLETED!");
try
{
WebBrowser webBrowser = sender as WebBrowser;
HtmlDocument doc = webBrowser.Document;
var button = doc.Body.Document.GetElementById("button");
button.InvokeMember("Click");
_browsers.Remove(webBrowser);
}
catch (Exception exp)
{
Console.WriteLine(exp.StackTrace);
MessageBox.Show(exp.Message);
}
}
}
You can access the WebBrowser document content using the following (you are missing body and need to type document to dynamic).
dynamic doc = browser.Document;
var button = doc.body.document.getElementById("button");
button.Click();
I found the solution very next day. Sorry for the late post by processing threads one by one by putting the statement after thread.sleep()
if (th.ThreadState == ThreadState.Aborted || th.ThreadState == ThreadState.Stopped)

Categories

Resources