I have tried to install an exe developed using Wix installer. After installation completed, tried to restart the system. Following sample logic I used.
Samples :
private void btn_RestartYes_Click(object sender, RoutedEventArgs e)
{
Thread thread = new Thread(new ThreadStart(RestartThreadFunction));
thread.Start();
this.Close();
SyncBA.Model.Engine.Quit(0);
}
public void RestartThreadFunction()
{
try
{
Process.Start("shutdown", "/r");
}
catch (Exception ex)
{
SyncBA.Model.Engine.Log(LogLevel.Error, ex.Message);
}
}
private void btn_RestartLater_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
( OR )
private void btn_RestartYes_Click(object sender, RoutedEventArgs e)
{
RestartThreadFunction();
}
public void RestartThreadFunction()
{
try
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.WindowStyle = ProcessWindowStyle.Hidden;
proc.FileName = "cmd";
proc.Arguments = "/C shutdown -f -r";
Process.Start(proc);
SyncBA.Model.Engine.Quit(0);
this.Close();
}
catch (Exception ex)
{
SyncBA.Model.Engine.Log(LogLevel.Error, ex.Message);
}
}
private void btn_RestartLater_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
Above logic is successfully working fine. After restarted the system "exe" uninstall window appear.
How to resolve an uninstall window appear issue after restart the system?
Thanks in advance!!
Related
Hi Friends i have written the program for minimize the form into system tray it is working fine for the minimize and in tray i can see new icon is appeared.
and in double click it restores, But the error is when i restore the form into its normal state then some labels are automatically goes visible false and the timer i have used in form that timer automatically stops please let me know if anyone have faced the same issue and have any idea about this issue.
please refer below code
private void User_Projects_SizeChanged(object sender, EventArgs e)
{
try
{
bool Mousepointontaskbar = Screen.GetWorkingArea(this).Contains(Cursor.Position);
if (this.WindowState == FormWindowState.Minimized && Mousepointontaskbar)
{
notifyIcon1.Icon = SystemIcons.Application;
notifyIcon1.BalloonTipText = "Tracker Has bin Minimized in System Tray";
notifyIcon1.ShowBalloonTip(1000);
this.ShowInTaskbar = false;
notifyIcon1.Visible = true;
//this.SizeChanged += new EventHandler(User_Projects_SizeChanged);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void User_Projects_Resize(object sender, EventArgs e)
{
this.Resize += new EventHandler(User_Projects_SizeChanged);
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
this.WindowState = FormWindowState.Normal;
if (this.WindowState == FormWindowState.Normal)
{
this.ShowInTaskbar = true;
this.Visible = true;
notifyIcon1.Visible = false;
}
}
I create a windows service and a setup project.
During the installation of the windows service, I add a windows form which allow the user to upload a file in the project folder but when I click on the button to upload the file my windows form is always on state not responding
ProjectInstaller of my windows service
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
Form1 validationForm = new Form1();
validationForm.ShowDialog();
}
Windows form
public Form1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, EventArgs e)
{
try
{
OpenFileDialog fileDialog = new OpenFileDialog();
//fileDialog.Filter = "Dat files |*.dat";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
var path = fileDialog.FileName;
Process.Start(path);
}
}
catch (Exception)
{
MessageBox.Show("An error occured", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I think Process.Start(path); block UI thread.
Try to use Task.Run(() => Process.Start(a)); instead.
Your UI is locked up due to a long running process which is why you see "Not responding"
Mark your Click Async:
private async void button1_Click_1(object sender, EventArgs e)
and
await Task.Run(() =>
{
//Insert the long running stuff here
Process.Start(path);
});
Try this.
private void button1_Click(object sender, EventArgs e)
{
var task = new Thread(() => GetFile());
task.SetApartmentState(ApartmentState.STA);
task.Start();
task.Join();
}
private static void GetFile()
{
try
{
OpenFileDialog fileDialog = new OpenFileDialog();
//fileDialog.Filter = "Dat files |*.dat";
fileDialog.Multiselect = false;
if (fileDialog.ShowDialog() == DialogResult.OK)
{
var path = fileDialog.FileName;
Process.Start(path);
}
}
catch (Exception)
{
MessageBox.Show("An error occured", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I am trying to show a message on loading of the application. I am trying to implement this using the Windows notifyIcon tool. Below is the method I implemented and calling this in the form load. However no message is being shown when opening my application.
private void Displaynotify()
{
try
{
//notifyIcon1.Icon = new System.Drawing.Icon(Path.GetFullPath(#"image\graph.ico"));
notifyIcon1.Text = "Finance - Treasury Ticket Notification";
notifyIcon1.Visible = true;
notifyIcon1.BalloonTipTitle = "Welcome, you have 3 Pending Tickets.";
notifyIcon1.BalloonTipText = "Click Here to see details";
notifyIcon1.ShowBalloonTip(100);
}
catch (Exception ex)
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
Displaynotify();
}
I have been working on a manager application for a Minecraft server, when I run my program, the console shows and disappears, if I run it manually, it runs without and problems.
Batch file code:
java -Xmx1024M -jar craftbukkit-1.7.2-R0.3.jar -o false
My full code (MessageBoxes are in Polish, becouse im from Poland, but later i will add support for other languages):
using System;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Process server;
private Boolean runServer()
{
if (!File.Exists(textBox2.Text))
{
MessageBox.Show("Brak określonej ścieżki dostępu! (" + textBox2.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
Process process = new Process
{
StartInfo =
{
FileName = textBox2.Text,
//Arguments = textBox3.Text,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = false,
}
};
process.OutputDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
process.ErrorDataReceived += new DataReceivedEventHandler(server_outputDataReceived);
server = process;
if (process.Start())
return true;
else
{
MessageBox.Show("Nie można włączyć serwera!", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private String ReadFile(String filename, int line)
{
StreamReader reader = new StreamReader(filename);
for (int i = 0; i < line; i++)
{
reader.ReadLine();
}
return reader.ReadLine();
}
private void ReloadOPs()
{
if (!File.Exists(textBox1.Text))
{
MessageBox.Show("Sciezka dostępu do pliku z listą graczy posiadających OP nie istnieje! (" + textBox1.Text + ")", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
tabControl1.SelectedTab = tabPageOptions;
textBox1.SelectAll();
return;
}
String line = ReadFile(textBox1.Text, 0);
comboBox1.Items.Clear();
for (int i = 1; i < File.ReadAllLines(textBox1.Text).Length; i++)
{
if (!String.IsNullOrWhiteSpace(ReadFile(textBox1.Text, i)))
{
comboBox1.Items.Add(line);
line = ReadFile(textBox1.Text, i);
}
}
MessageBox.Show("Lista graczy z OP, została odświeżona.");
}
// OPs combobox (OPs)
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
groupBox1.Text = comboBox1.SelectedItem.ToString();
groupBox1.Visible = true;
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = Application.StartupPath.ToString() + #"\ops.txt";
ReloadOPs();
}
// Reload OPs button (OPs)
private void button1_Click(object sender, EventArgs e)
{
ReloadOPs();
}
// Save button (Options)
private void button4_Click(object sender, EventArgs e)
{
}
private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
{
addConsoleMessage(e.Data.ToString(), true);
}
// Run server button (Menu)
private void button5_Click(object sender, EventArgs e)
{
if (!runServer())
return;
server.BeginOutputReadLine();
button6.Enabled = true;
}
// Stop server button (Menu)
private void button6_Click(object sender, EventArgs e)
{
if(!server.HasExited)
server.Kill();
button6.Enabled = false;
}
private void addConsoleMessage(String message, Boolean refresh)
{
listBox1.Items.Add(message);
if (refresh)
listBox1.Refresh();
}
}
}
My problem is that program crashes becouse InvaildOperationException was unhandled (listBox1.Items.Add(message) in addConsoleMessage).
External error information: Invalid operation between threads: the control 'listBox1' is accessed from a thread other than the thread it was created.
You cannot update UI form background thread. Try this
WPF
private void server_outputDataReceived(object sender, DataReceivedEventArgs e)
{
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, () =>
{
addConsoleMessage(e.Data.ToString(), true);
});
}
Update
In WinForms the Invoke/BeginInvoke methods are directly on the control objects as you can see from the docs of System.Windows.Forms.Control. So you'd have listBox1.BeginInvoke(...) for example.
I have a C# winform application which needs to run multiple instance in synchronous way. The goal is to:
If the exe runs 3 times, it runs the first instance of the exe and the rest will wait until the first instance finishes the processing. Then, a next waiting exe intance will run and process and so on.
The exe will run one by one until it finish processing then the exe will terminates automatically af.
Any idea how to do this?
I already tried below:
private void CheckInstance()
{
bool _returnValue = true;
string _lockFile = string.Empty;
Random _rnd = new Random();
int _randomValue = _rnd.Next(100, 200);
int _rndmiliSec = 0;
_rndmiliSec = DateTime.Now.Millisecond * _rnd.Next(2, 6);
_lockFile = string.Concat(AppDomain.CurrentDomain.BaseDirectory, string.Format("/{0}", instanceFileName));
while (_returnValue)
{
_returnValue = File.Exists(_lockFile);
if (_returnValue)
{
Thread.Sleep(1000);
this.Hide();
}
else
{
try
{
Thread.Sleep((_rnd.Next(1000) + _rndmiliSec) + _rnd.Next(1000, 1500));
Functions.WriteLog(_lockFile, "Starting the process...");
Functions.WriteLog(_lockFile, string.Format("Start Time : {0}", paramPrintTime));
File.SetAttributes(_lockFile, FileAttributes.ReadOnly);
this.Show();
break;
}
catch (Exception)
{
_returnValue = false;
}
}
}
}
private void DeleteInstance()
{
try
{
File.SetAttributes(string.Concat(AppDomain.CurrentDomain.BaseDirectory, string.Format("/{0}", instanceFileName)), FileAttributes.Normal);
File.Delete(string.Concat(AppDomain.CurrentDomain.BaseDirectory, string.Format("/{0}", instanceFileName)));
}
catch (Exception)
{
}
}
private void Form_Shown(Object sender, EventArgs e)
{
_backWorker.RunWorkerAsync();
}
private void FormClosed(object sender, FormClosedEventArgs e)
{
DeleteInstance();
}
private void Form_Load(object sender, System.EventArgs e)
{
CheckInstance();
}
BackgroundWorker _backWorker = new BackgroundWorker();
public Form()
{
InitializeComponent();
_backWorker.WorkerReportsProgress = true;
_backWorker.ProgressChanged += _backWorker_ProgressChanged;
_backWorker.RunWorkerCompleted += _backWorker_RunWorkerCompleted;
_backWorker.DoWork += _backWorker_DoWork;
}
private void _backWorker_DoWork(object sender, DoWorkEventArgs e)
{
Do some work processing...
}
private void _backWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
private void _backWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pg.Value = e.ProgressPercentage;
lblIndicator.Text = e.UserState.ToString();
}
When the exe run 3 instance, the first instance will run while 2nd and third hides for a while awaiting the 1st instance to be finisih. However, after the 1st instance finish the process, The 2nd and 3rd instance are running simultaneously.
Any Ideas? Thanks.
Maybe this can work:
public static bool IsProgramRunning(string TitleOfYourForm)
{
bool result = false;
Process[] processes = Process.GetProcesses();
foreach (Process p in processes)
{
if (p.MainWindowTitle.Contains(TitleOfYourForm))
{
result = true;
break;
}
}
return result;
}
Call this function in the Main function(before opening the mainForm), if it is false Application.Exit() else show your form..
If this answer helped you, vote me.