The invocation of the constructor on type 'WpfApplication1.MainWindow'
that matches the specified binding constraints threw an exception.'
Line number '4' and line position '9'.
That was the error I'm facing while changing my target platform from 'x86' to 'Any CPU' in order to run my executable to run in x86 and x64 bit windows operating systems.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WebKit;
using WebKit.Interop;
using Twitterizer;
using Facebook;
using TwitterConnect;
using facebook;
namespace WpfApplication3
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
WebKitBrowser wb = new WebKitBrowser();
TwitterConnect.TwitterStuff ts = new TwitterStuff();
Browser b = new Browser();
OpenWebkitBrowser.facebook fb_1 = new OpenWebkitBrowser.facebook();
private void Possibillion_Loaded(object sender, RoutedEventArgs e)
{
System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost();
host.Child = wb;
this.Grid2.Children.Add(host);
wb.DocumentCompleted += wb_DocumentCompleted;
}
void wb_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
textBox1.Text = wb.Url.ToString();
TabItem1.Header = wb.DocumentTitle;
}
private void btnMinimize_Click(object sender, RoutedEventArgs e)
{
Possibillion.WindowState = WindowState.Minimized;
}
private void btnMaximize_Click(object sender, RoutedEventArgs e)
{
if (Possibillion.WindowState == WindowState.Maximized)
Possibillion.WindowState = WindowState.Normal;
else
Possibillion.WindowState = WindowState.Maximized;
}
private void btnClose_Click(object sender, RoutedEventArgs e)
{
Possibillion.Close();
}
private void btnGo_Click(object sender, RoutedEventArgs e)
{
wb.Navigate("http://" + textBox1.Text);
}
private void btnTwitter_Click(object sender, RoutedEventArgs e)
{
bool loggedIn = b.AlreadyLoggedIn();
if (!loggedIn)
{
//this.Hide();
b.Show();
}
//else
//{
// MainWindow mw = new MainWindow();
// mw.Show();
// this.Close();
//}
else if (textBox1.Text != "")
{
ts.tweetIt(wb.DocumentTitle);
//textBox1.Clear();
}
}
private void btnfacebook_Click_1(object sender, RoutedEventArgs e)
{
if (val.login == true)
{
//fb_1.Show();
if (string.IsNullOrEmpty(textBox1.Text))
{
Dispatcher.Invoke(new Action(() => { System.Windows.MessageBox.Show("Enter message."); }));
return;
}
var fb = new FacebookClient(val.token);
fb.PostCompleted += (o, args) =>
{
if (args.Error != null)
{
Dispatcher.Invoke(new Action(() => { System.Windows.MessageBox.Show(args.Error.Message); }));
return;
}
var result = (IDictionary<string, object>)args.GetResultData();
//_lastMessageId = (string)result["id"];
Dispatcher.Invoke(new Action(() =>
{
System.Windows.MessageBox.Show("Message Posted successfully");
textBox1.Text = string.Empty;
// pho.IsEnabled = true;
}));
};
var fbimg = new Facebook.FacebookMediaObject
{
FileName = Guid.NewGuid() + ".jpg",
ContentType = "image/png"
};
// FileStream fs = new FileStream("Rose.png", FileMode.Open, FileAccess.Read);
// BinaryReader br = new BinaryReader(fs);
// byte[] res = br.ReadBytes((int)fs.Length);
// br.Close();
// fs.Close();
//fbimg.SetValue(res);
// Uri uri = new Uri("/Background.png",UriKind.Relative);
var parameters = new Dictionary<string, object>();
//parameters.Add("picture", fbimg);
//parameters.Add("message", "hi");
// parameters["picture"] ="https://twimg0-a.akamaihd.net/profile_images/2263781693/SAchin_reasonably_small.png";
parameters["message"] = textBox1.Text;
// parameters["picture"] =fbimg;
//fb.PostAsync(#"/photos", parameters);
fb.PostAsync("me/feed", parameters);
}
else
{
Dispatcher.Invoke(new Action(() => { fb_1.ShowDialog(); }));
//System.Windows.MessageBox.Show("message not sent");
}
}
private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
wb.Navigate("http://" + textBox1.Text);
}
}
}
Make sure your target platform matches your build settings.
If you have changed your configuration manager to any CPU, then in the project properties under build you will need to do the same.
Edit - Ah seems like your trying to run a toolkit that is build for x86 in a x64 world.
Related
Link for the repository on github :
https://github.com/chocolade1972/FileSystemWatcher
At the top i init with new instance both filelist and dic variables.
Then when starting watching i get all the files . and add them to the filelist and to the dic.
If for example the path is C:\ then filelist will contain 6 items :
filelist = Directory.GetFiles(textBox_path.Text, "*.*").ToList();
foreach (var item in filelist)
{
FileInfo info = new FileInfo(item);
dic.Add(item, info.Length);
}
Then in the event Watcher_Changes at this line :
var info = new FileInfo(e.FullPath);
There is exception the file not found and i see when using a breakpoint a long file temp type with tmp extension.
Then on other files it's throwing exceptions key was not present and then if i will start watching over again it will throw exceptions that the key is the same and already exist.
Other problem is now the button Button_doit in the event Button_doit_Click is not changing to stop and stay on start all the time.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
namespace Watcher_WPF
{
/// <summary>
/// MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Watcher watcher;
private List<string> filelist = new List<string>();
private Dictionary<string, long> dic = new Dictionary<string, long>();
public MainWindow()
{
InitializeComponent();
CenterWindowOnScreen();
var nf = new NFilters()
{
Size = true,
FileName = true,
DirectoryName = true,
};
watcher = new Watcher(nf);
watcher.Created += Watcher_Changes;
watcher.Changed += Watcher_Changes;
watcher.Deleted += Watcher_Changes;
watcher.Renamed += Watcher_Renamed;
PrintMsg(Application.ResourceAssembly.ToString());
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (watcher.IsStarted)
{
e.Cancel = MessageBox.Show("Watcher is working, are you sure to close?", "Oh!",
MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No;
}
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
//Ctrl
if (e.KeyboardDevice.IsKeyDown(Key.LeftCtrl) || e.KeyboardDevice.IsKeyDown(Key.RightCtrl))
{
if (e.KeyboardDevice.IsKeyDown(Key.S))
{
//Ctrl+S
SaveLogs(null, null);
}
else if (e.KeyboardDevice.IsKeyDown(Key.D))
{
//Ctrl+D
ClearLogs(null, null);
}
}
}
private void Button_doit_Click(object sender, RoutedEventArgs e)
{
try
{
if (!watcher.IsStarted)
{
SetPath(textBox_path.Text.Trim());
}
watcher.IsStarted = !watcher.IsStarted;
if(button_doit.Content.ToString() == "Stop")
{
add_path.IsEnabled = true;
}
else
{
add_path.IsEnabled = false;
RandomFiles.GenerateFiles();
filelist = Directory.GetFiles(textBox_path.Text, "*.*").ToList();
foreach (var item in filelist)
{
FileInfo info = new FileInfo(item);
dic.Add(item, info.Length);
}
}
button_doit.Content = watcher.IsStarted ? "Stop" : "Start";
button_doit.Foreground = watcher.IsStarted ? Brushes.Red : Brushes.Black;
textBox_path.IsEnabled = !watcher.IsStarted;
PrintMsg(watcher.IsStarted ? "watcher started...At " + DateTime.Now.ToString() : "watcher stopped...At " + DateTime.Now.ToString());
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Button_options_Click(object sender, RoutedEventArgs e)
{
options.IsOpen = true;
}
private void OptionsMenu_Opened(object sender, RoutedEventArgs e)
{
allow_edit.IsChecked = !richTextBox_main.IsReadOnly;
topmost_switcher.IsChecked = Topmost;
filter_setter.IsEnabled = !watcher.IsStarted;
include_subdir.IsEnabled = !watcher.IsStarted;
include_subdir.IsChecked = watcher.IncludeSubdirectories;
}
private void AddPath(object sender, RoutedEventArgs e)
{
// Configure open file dialog box
var dialog = new Microsoft.Win32.OpenFileDialog();
dialog.FileName = "Document"; // Default file name
dialog.DefaultExt = ".*"; // Default file extension
dialog.Filter = "All files|*.*"; // Filter files by extension
// Show open file dialog box
bool? result = dialog.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
textBox_path.Text = dialog.FileName;
}
}
private void SaveLogs(object sender, RoutedEventArgs e)
{
try
{
SaveFileDialog sfd = new SaveFileDialog()
{
Filter = "TXT|*.txt",
FileName = $"watcher_{DateTime.Now:yyyyMMddHHmmss}"
};
if (sfd.ShowDialog() == true)
{
string path = sfd.FileName;
string content = new TextRange(
richTextBox_main.Document.ContentStart,
richTextBox_main.Document.ContentEnd).Text;
File.WriteAllText(path, content);
PrintMsg($"saved log to \"{path}\"");
}
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void ClearLogs(object sender, RoutedEventArgs e)
{
richTextBox_main.Document.Blocks.Clear();
}
private void Switch_Window_Topmost(object sender, RoutedEventArgs e)
{
Topmost = !Topmost;
}
private void Allow_edit_Click(object sender, RoutedEventArgs e)
{
richTextBox_main.IsReadOnly = !richTextBox_main.IsReadOnly;
}
private void Filter_setter_Click(object sender, RoutedEventArgs e)
{
var tmp = new FilterWindow(watcher.NFilters, watcher.Filter) { Owner = this }.ShowDialog();
if (tmp is Fdr fdr)
{
watcher.Filter = fdr.Filter;
watcher.NFilters = fdr.Nfilters;
PrintMsg($"set Filter: Size={watcher.NFilters.Size}, FileName={watcher.NFilters.FileName}, " +
$"DirectoryName={watcher.NFilters.DirectoryName}, Filter=\"{watcher.Filter}\"");
}
}
private void Include_subdir_Click(object sender, RoutedEventArgs e)
{
watcher.IncludeSubdirectories = !watcher.IncludeSubdirectories;
PrintMsg($"IncludeSubdirectories={watcher.IncludeSubdirectories}");
}
private void View_source_code_Click(object sender, RoutedEventArgs e)
{
Process.Start("https://github.com/Mzying2001/Watcher_WPF");
}
private void TextBox_path_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
Button_doit_Click(null, null);
}
private void RichTextBox_main_TextChanged(object sender, TextChangedEventArgs e)
{
if (richTextBox_main.IsReadOnly)
richTextBox_main.ScrollToEnd();
}
private void SetPath(string path)
{
watcher.Path = path;
PrintMsg($"set path: \"{watcher.Path}\"");
}
private void Watcher_Changes(object sender, FileSystemEventArgs e)
{
try
{
if (e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Deleted)
{
}
else
{
var info = new FileInfo(e.FullPath);
var newSize = info.Length;
var oldsize = dic[e.FullPath];
string FileN1 = "File Name : ";
string FileN2 = info.Name;
string FileN3 = " Size Has Changed : From ";
string FileN4 = oldsize.ToString();
string FileN5 = " To ";
string FileN6 = newSize.ToString();
if (newSize != oldsize)
{
//string output = $"[*] {e.ChangeType}: \"{e.FullPath}\"";
Println(FileN1 + FileN2 + FileN3 + FileN4 + FileN5 + FileN6);
}
if (dic.ContainsKey(e.FullPath))
{
dic[e.FullPath] = info.Length;
}
else
{
dic.Add(e.FullPath, info.Length);
}
}
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Watcher_Renamed(object sender, RenamedEventArgs e)
{
try
{
Println($"[*] {e.ChangeType}: \"{e.OldFullPath}\" -> \"{e.FullPath}\"");
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Println(string text, SolidColorBrush brush) => Dispatcher.Invoke(() =>
{
richTextBox_main.Document.Blocks.Add(new Paragraph(new Run(text) { Foreground = brush }));
});
private void Println(string text)
{
Println("[+] " + text + " At : " + DateTime.Now.ToString(), Brushes.LawnGreen);
}
private void PrintMsg(string message)
{
Println($"[+] {message}", Brushes.Yellow);
}
private void PrintErr(Exception e)
{
Println($"[-] {e}", Brushes.Red);
}
private void CenterWindowOnScreen()
{
double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
double windowWidth = this.Width;
double windowHeight = this.Height;
this.Left = (screenWidth / 2) - (windowWidth / 2);
this.Top = (screenHeight / 2) - (windowHeight / 2);
}
private byte[] CheckSize(string filename)
{
using (MD5 md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
return md5.ComputeHash(stream);
}
}
}
private void textBox_path_TextChanged(object sender, TextChangedEventArgs e)
{
if (button_doit != null)
{
if (textBox_path.Text == "")
{
button_doit.IsEnabled = false;
}
else
{
button_doit.IsEnabled = true;
}
}
}
}
}
I have sort of found a solution to the question My previous question and it was to use:
SendKeys.Send("{ENTER}"); to automatically click OK button on a dialog box
My problem now is that SendKeys.Send("{ENTER}"); will work in an event method i.e Start_click but will not in the method Start_Vid();
I get the error:
'SendKeys cannot run inside this application because the application is not handling Windows messages. Either change the application to handle messages, or use the SendKeys.SendWait method'
I have no idea why it should not work and what the error message means?
The code is below:
using System;
using System.Threading;
using System.Windows.Input;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using Accord.Video.FFMPEG;
using AForge.Video.VFW;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private FilterInfoCollection VideoCaptureDevices;
private VideoCaptureDevice FinalVideo = null;
private VideoCaptureDeviceForm captureDevice;
private Bitmap video;
private VideoFileWriter FileWriter = new VideoFileWriter();
private SaveFileDialog saveAvi;
public Form1()
{
InitializeComponent();
Console.WriteLine(date1);
Console.WriteLine(date2);
Console.WriteLine(date3);
Console.WriteLine(date3);
Start_Vid();
}
private void Form1_Load(object sender, EventArgs e)
{
VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
captureDevice = new VideoCaptureDeviceForm();
}
void FinalVideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (Stop.Text == "Stop Record")
{
video = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
//AVIwriter.Quality = 0;
FileWriter.WriteVideoFrame(video);
//AVIwriter.AddFrame(video);
}
else
{
video = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
}
}
private void Stop_Vid()
{
if (Stop.Text == "Stop Record")
{
Stop.Text = "Stop";
if (FinalVideo == null)
{ return; }
if (FinalVideo.IsRunning)
{
//this.FinalVideo.Stop();
FileWriter.Close();
//this.AVIwriter.Close();
pictureBox1.Image = null;
}
}
else
{
this.FinalVideo.Stop();
FileWriter.Close();
//this.AVIwriter.Close();
pictureBox1.Image = null;
}
}
private void butstop_Click(object sender, EventArgs e)
{
if (Stop.Text == "Stop Record")
{
Stop.Text = "Stop";
if (FinalVideo == null)
{ return; }
if (FinalVideo.IsRunning)
{
//this.FinalVideo.Stop();
FileWriter.Close();
//this.AVIwriter.Close();
pictureBox1.Image = null;
}
}
else
{
this.FinalVideo.Stop();
FileWriter.Close();
//this.AVIwriter.Close();
pictureBox1.Image = null;
}
}
private void button3_Click(object sender, EventArgs e)
{
pictureBox1.Image.Save("IMG" + DateTime.Now.ToString("hhmmss") + ".jpg");
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalVideo == null)
{ return; }
if (FinalVideo.IsRunning)
{
this.FinalVideo.Stop();
FileWriter.Close();
//this.AVIwriter.Close();
}
}
private void Save_Click(object sender, EventArgs e)
{
saveAvi = new SaveFileDialog();
saveAvi.Filter = "Avi Files (*.avi)|*.avi";
saveAvi.FileName = "New Vid1";
if (saveAvi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int h = captureDevice.VideoDevice.VideoResolution.FrameSize.Height;
int w = captureDevice.VideoDevice.VideoResolution.FrameSize.Width;
FileWriter.Open(saveAvi.FileName, w, h, 25, VideoCodec.Default, 5000000);
FileWriter.WriteVideoFrame(video);
//AVIwriter.Open(saveAvi.FileName, w, h);
Stop.Text = "Stop Record";
//FinalVideo = captureDevice.VideoDevice;
//FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
//FinalVideo.Start();
}
}
//##############################################//
// Method not working //
//##############################################//
private void Start_Vid()
{
SendKeys.Send("{ENTER}");
if (captureDevice.ShowDialog(this) == DialogResult.OK)
{
VideoCaptureDevice videoSource = captureDevice.VideoDevice;
FinalVideo = captureDevice.VideoDevice;
FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
FinalVideo.Start();
}
}
//##############################################//
// Method working //
//##############################################//
private void Start_Click(object sender, EventArgs e)
{
SendKeys.Send("{ENTER}");
if (captureDevice.ShowDialog(this) == DialogResult.OK)
{
VideoCaptureDevice videoSource = captureDevice.VideoDevice;
FinalVideo = captureDevice.VideoDevice;
FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
FinalVideo.Start();
}
}
private void Close_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Try using the SendKeys.SendWait method.
If it doesn't work try this AutoHotKey wrapper from andrew.
And by using these lines of code should do the trick.
var ahk = AutoHotkeyEngine.Instance;
ahk.ExecRaw("Send {Enter}");
i am sending Sensor information with a NUCLEOF411RE to my PC. I receive this data on the COM98 with a BaudRate of 115200. Now i want to program a Windows Application that will split my string and put it on my textboxes. until now i display the data with a Button_click event. It puts values on the Textboxes that actually are the real values. But if i move my Sensor and klick the button again there should be a lot more different values, but there are the same values on the textboxes. In addition i want to refresh the textboxes automatically and not with a button click.
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.IO.Ports;
namespace BNO080
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getAvailablePorts();
}
public string comport;
SerialPort serial = new SerialPort();
void getAvailablePorts()
{
String[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
comport = comboBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if(comboBox1.Text=="" || textBox6.Text=="")
{
MessageBox.Show("Please Select Port Settings");
}
else
{
serial.PortName = comboBox1.Text;
serial.BaudRate = Convert.ToInt32(textBox6.Text);
serial.Parity = Parity.None;
serial.StopBits = StopBits.One;
serial.DataBits = 8;
serial.Handshake = Handshake.None;
serial.Open();
MessageBox.Show("connected!");
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Unauthorised Access");
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
MessageBox.Show("connection closed!");
serial.Close();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
textBox5.Text = serial.ReadLine();
/*String[] Stringsizes = A.Split(new char[] {' '});
textBox1.Text = Stringsizes[0];
textBox2.Text = Stringsizes[1];
textBox3.Text = Stringsizes[2];
textBox4.Text = Stringsizes[3];*/
// textBox5.Text = A;
//Array.Clear(Stringsizes, 0, 3);
}
catch (Exception) { }
}
}
}
can someone help me?
Can you give more information why you use the Button_Click Event to read the text? Maybe it is a possible way for you to subscribe for the DataReceived-Event of the COM-port?
It would look something like this:
serial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
string receivedString = serial.ReadExisting();
//Do something here...
}
I'd do a couple things. First subscribe to the DataReceived event on the serial port. This event handler will get called when there is data available on the serial port. Then in the event handler you can read from the serial port and add it to your textbox. You can't add it directly (see the AppendText function) because the event handler is called with a different thread, only the UI thread can update UI components (or you'll get a cross-thread exception).
...
public Form1()
{
InitializeComponent();
getAvailablePorts();
// Subscribe to the DataReceived event. Our function Serial_DataReceived
// will be called whenever there's data available on the serial port.
serial.DataReceived += Serial_DataReceived;
}
// Appends the given text to the given textbox in a way that is cross-thread
// safe. This can be called by any thread, not just the UI thread.
private void AppendText(TextBox textBox, string text)
{
// If Invoke is required, i.e. we're not running on the UI thread, then
// we need to invoke it so that this function gets run again but on the UI
// thread.
if (textBox.InvokeRequired)
{
textBox.BeginInvoke(new Action(() => AppendText(textBox, text)));
}
// We're on the UI thread, we can append the new text.
else
{
textBox.Text += text;
}
}
// Gets called whenever we receive data on the serial port.
private void Serial_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
string serialData = serial.ReadExisting();
AppendText(textBox5, serialData);
}
Because i want to add an rotating 3D cube i decided to switch to WPF. I heard it is much easier to implement a 3D graphic there. So i copied my code to the new WPF project. But now i got already problems to visualize my values on the Textboxes. It doesnt work. It looks like the Evenhandler did not fire an event while receiving Data from the com port.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Drawing;
namespace cube
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
getAvailablePorts();
serial.DataReceived += Serial_DataReceived;
}
public bool button3clicked = false;
public bool button4clicked = false;
public bool button5clicked = false;
SerialPort serial = new SerialPort();
void getAvailablePorts()
{
List<string> Itemlist = new List<string>();
String[] ports = SerialPort.GetPortNames();
Itemlist.AddRange(ports);
comboBox1.ItemsSource = Itemlist;
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || textBox6.Text == "")
{
MessageBox.Show("Please Select Port Settings");
}
else
{
serial.PortName = comboBox1.Text;
serial.BaudRate = Convert.ToInt32(textBox6.Text);
serial.Parity = Parity.None;
serial.StopBits = StopBits.One;
serial.DataBits = 8;
serial.Handshake = Handshake.None;
serial.Open();
MessageBox.Show("connected!");
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Unauthorised Access");
}
}
private void button2_Click_1(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
MessageBox.Show("connection closed!");
serial.Close();
textBox1.Text = "test";
}
private void AppendText(string[] text)
{
try
{
textBox1.Text = text[0];
textBox2.Text = text[1];
textBox3.Text = text[2];
textBox4.Text = text[3];
}
catch (Exception) { }
}
private void Safe_Position1(TextBox tBr1, TextBox tBi1, TextBox tBj1, TextBox tBk1, string[] text)
{
if (button3clicked == true)
{
tBr1.Text = text[0];
tBi1.Text = text[1];
tBj1.Text = text[2];
tBk1.Text = text[3];
button3clicked = false;
}
}
private void Safe_Position2(TextBox tBr2, TextBox tBi2, TextBox tBj2, TextBox tBk2, string[] text)
{
if (button4clicked == true)
{
tBr2.Text = text[0];
tBi2.Text = text[1];
tBj2.Text = text[2];
tBk2.Text = text[3];
button4clicked = false;
}
}
private void Safe_Position3(TextBox tBr3, TextBox tBi3, TextBox tBj3, TextBox tBk3, string[] text)
{
if (button5clicked == true)
{
tBr3.Text = text[0];
tBi3.Text = text[1];
tBj3.Text = text[2];
tBk3.Text = text[3];
button5clicked = false;
}
}
private void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string serialData = serial.ReadLine();
String[] text = serialData.Split(new char[] { ' ' });
AppendText(text);
Safe_Position1(textBox5, textBox7, textBox8, textBox9, text);
Safe_Position2(textBox10, textBox11, textBox12, textBox13, text);
Safe_Position3(textBox14, textBox15, textBox16, textBox17, text);
}
private void button3_Click(object sender, EventArgs e)
{
button3clicked = true;
}
private void button4_Click(object sender, EventArgs e)
{
button4clicked = true;
}
private void button5_Click(object sender, EventArgs e)
{
button5clicked = true;
}
}
}
Here is a question very close to mine (I think): Running a method in BackGroundWorker and Showing ProgressBar
Here is my code, it's not freezing my Main form anymore but the function doesn't do its job.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using YoutubeSearch;
namespace searchyoutubeTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
myBGWorker.WorkerReportsProgress = true;
}
void myBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
myProgressBar.Value = e.ProgressPercentage;
}
void myBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnSearch.Enabled = true;
MessageBox.Show("Done");
}
private void myBGWorker_DoWork(object sender, DoWorkEventArgs e)
{
VideoSearch items = new VideoSearch();
List<Video> list = new List<Video>();
foreach (var item in items.SearchQuery(txtSearch.Text, 1))
{
Video video = new Video();
video.Title = item.Title;
video.Author = item.Author;
video.Url = item.Url;
byte[] imageBytes = new WebClient().DownloadData(item.Thumbnail);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
video.Thumbnail = Image.FromStream(ms);
}
list.Add(video);
}
e.Result = list;
}
private void btnSearch_Click(object sender, EventArgs e)
{
btnSearch.Enabled = false;
myBGWorker.RunWorkerAsync();
//VideoSearch items = new VideoSearch();
//List<Video> list = new List<Video>();
//foreach (var item in items.SearchQuery(txtSearch.Text, 1))
//{
// Video video = new Video();
// video.Title = item.Title;
// video.Author = item.Author;
// video.Url = item.Url;
// byte[] imageBytes = new WebClient().DownloadData(item.Thumbnail);
// using (MemoryStream ms = new MemoryStream(imageBytes))
// {
// video.Thumbnail = Image.FromStream(ms);
// }
// list.Add(video);
//}
//videoBindingSource.DataSource = list;
}
private void txtSearch_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnSearch_Click(this, new EventArgs());
}
}
}
}
But if I do only the function, it works:
//VideoSearch items = new VideoSearch();
//List<Video> list = new List<Video>();
//foreach (var item in items.SearchQuery(txtSearch.Text, 1))
//{
// Video video = new Video();
// video.Title = item.Title;
// video.Author = item.Author;
// video.Url = item.Url;
// byte[] imageBytes = new WebClient().DownloadData(item.Thumbnail);
// using (MemoryStream ms = new MemoryStream(imageBytes))
// {
// video.Thumbnail = Image.FromStream(ms);
// }
// list.Add(video);
//}
//videoBindingSource.DataSource = list;
Any idea what I am doing wrong?
I assume you correctly added the events for the button and onload of the form.
You didnt attach the events for the BackgroundWorker. When you click on the searchbutton, the workers starts and the DoWork method is invoked on a seperate thread.
public Form1()
{
InitializeComponent();
myBGWorker.WorkerReportsProgress = true;
myBGWorker.DoWork += myBGWorker_DoWork;
myBGWorker.ProgressChanged += myBGWorker_ProgressChanged;
myBGWorker.RunWorkerCompleted += myBGWorker_RunWorkerCompleted;
}
I am trying to send custom commands to a service using a windows form. The command I am trying to send is trying to place a file in Isolated Storage. Below is my source code.
Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Project2Service;
namespace Project2
{
public partial class Form1 : Form
{
public Service1 s = new Service1();
public ServiceInstaller si = new ServiceInstaller();
public ProjectInstaller pi = new ProjectInstaller();
public ServiceController sc = new ServiceController("Project2Service");
private string[] isoType;
string machineName = System.Windows.Forms.SystemInformation.ComputerName;
public Form1()
{
InitializeComponent();
isoType = new string[] { "User", "Assembly And Domain"};
cboIsoType.Items.AddRange(isoType);
cboIsoType.SelectedIndex = 0;
btnContinue.Enabled = false;
btnPause.Enabled = false;
btnStop.Enabled = false;
}
public void Labels()
{
lblMachine.Text = machineName;
lblSName.Text = s.ServiceName;
lblSType.Text = si.StartType.ToString();
lblSStatus.Text = sc.Status.ToString();
lblPause.Text = sc.CanPauseAndContinue.ToString();
lblShutdown.Text = sc.CanShutdown.ToString();
lblStop.Text = sc.CanStop.ToString();
}
private void btnStart_Click(object sender, EventArgs e)
{
//Controller.Refresh(); //Gets the current status of service
//if (Controller.Status == ServiceControllerStatus.Stopped)
//{
// Controller.Start();
//}
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
Labels();
btnStart.Enabled = false;
btnContinue.Enabled = false;
btnStop.Enabled = true;
btnPause.Enabled = true;
}
private void btnStop_Click(object sender, EventArgs e)
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);
Labels();
btnStart.Enabled = true;
btnContinue.Enabled = false;
btnPause.Enabled = false;
btnStop.Enabled = false;
}
private void btnPause_Click(object sender, EventArgs e)
{
sc.Pause();
sc.WaitForStatus(ServiceControllerStatus.Paused);
Labels();
btnPause.Enabled = false;
btnContinue.Enabled = true;
btnStart.Enabled = false;
btnStop.Enabled = true;
}
private void btnContinue_Click(object sender, EventArgs e)
{
sc.Continue();
sc.WaitForStatus(ServiceControllerStatus.Running);
Labels();
btnStop.Enabled = true;
btnStart.Enabled = false;
btnPause.Enabled = true;
btnContinue.Enabled = false;
}
private void btnSubmit_Click(object sender, EventArgs e)
{
if (cboIsoType.SelectedItem.ToString() == "User")
{
sc.ExecuteCommand(128);
}
}
}
}
Service
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Project2Service
{
public partial class Service1 : ServiceBase
{
public enum ServiceCustomCommands { Command1 = 128, Command2 = 129 };
//private IsolatedStorageScope iso;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//iso = IsolatedStorageScope.User | IsolatedStorageScope.Domain;
FileSystemWatcher Watcher = new FileSystemWatcher(#"C:\Users\Martin\Desktop\Project2\ServiceTest");
Watcher.EnableRaisingEvents = true;
Watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
Watcher.Changed += new FileSystemEventHandler(Watcher_Changed);
Watcher.Created += new FileSystemEventHandler(Watcher_Created);
Watcher.Deleted += new FileSystemEventHandler(Watcher_Deleted);
Watcher.Renamed += new RenamedEventHandler(Watcher_Renamed);
WriteServiceInfo("Service Started!");
}
// This event is raised when a file is changed
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Changed!");
DirectoryInfo d = new DirectoryInfo(#"C:\Users\Martin\Desktop\Project2\ServiceTest");//Assuming Watch is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
str = str + ", " + file.LastWriteTime;
str = str + ", " + file.CreationTime;
str = str + ", " + file.Length;
WriteServiceInfo(file.Name);
WriteServiceInfo(file.LastWriteTime.ToString());
WriteServiceInfo(file.CreationTime.ToString());
WriteServiceInfo(file.Length.ToString());
}
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Created!");
}
private void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Deleted!");
}
private void Watcher_Renamed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Renamed!");
}
private void WriteServiceInfo(string info)
{
FileStream fs = new FileStream(#"C:\Users\Martin\Desktop\Project2\WindowsServiceLog.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(info + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
protected override void OnStop()
{
WriteServiceInfo("Service Stopped!");
}
protected override void OnCustomCommand(int command)
{
switch ((ServiceCustomCommands)command)
{
case ServiceCustomCommands.Command1:
//Command1 Implementation
IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt", FileMode.Append, FileAccess.Write, isoFile);
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Data");
}
//iso = IsolatedStorageScope.User;
break;
case ServiceCustomCommands.Command2:
//iso = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;
break;
default:
break;
}
}
}
}
sc.ExecuteCommand(128); in the submit button method does not seem to fire.
This worked just fine for me so I surmise its your code not hitting the call to execute the command. I took your code, made it a bit easier.
For example - stripping out all the stuff above - this code below worked and the text file appeared with the "Command Received" in it.
In your case it could be that you aren't closing the file. Try this:
using (
IsolatedStorageFile isoFile =
IsolatedStorageFile.GetStore(
IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly,
null, null))
{
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt",
FileMode.Append, FileAccess.Write, isoFile);
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Data");
}
WriteServiceInfo("data written to isolated storage");
isoFile.Close();
}
I changed the submit button to simply send the command, I'd suggest the same
private void btnSubmit_Click(object sender, EventArgs e)
{
sc.ExecuteCommand(128);
}
Service code is as follows
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Project2Service
{
public partial class Service1 : ServiceBase
{
public enum ServiceCustomCommands { Command1 = 128, Command2 = 129 };
//private IsolatedStorageScope iso;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WriteServiceInfo("Service Started!");
}
// This event is raised when a file is changed
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Changed!");
}
private void Watcher_Created(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Created!");
}
private void Watcher_Deleted(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Deleted!");
}
private void Watcher_Renamed(object sender, FileSystemEventArgs e)
{
WriteServiceInfo("File Renamed!");
}
private void WriteServiceInfo(string info)
{
FileStream fs = new FileStream(#"C:\Users\Adam\Desktop\WindowsServiceLog.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(info + "\n");
m_streamWriter.Flush();
m_streamWriter.Close();
}
protected override void OnStop()
{
WriteServiceInfo("Service Stopped!");
}
protected override void OnCustomCommand(int command)
{
WriteServiceInfo("Command received");
switch ((ServiceCustomCommands)command)
{
case ServiceCustomCommands.Command1:
//Command1 Implementation
IsolatedStorageFile isoFile = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("LaptopInfo.txt", FileMode.Append, FileAccess.Write, isoFile);
using (StreamWriter writer = new StreamWriter(isoStream))
{
writer.WriteLine("Data");
}
//iso = IsolatedStorageScope.User;
break;
case ServiceCustomCommands.Command2:
//iso = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;
break;
default:
break;
}
}
}
}