start and stop data saving on .txt file using button on c# - c#

I have a sensor that connected to pc and data comes continuously like this picture:
I want to add two start and stop button and save data from start button pressed time and stop saving data when pressed stop button.
I write this code:
richTextBox1.AppendText(textBox1.Text + "\n");
System.IO.File.WriteAllLines(#"C:\Users\Mohammad_Taghi\Desktop\a.txt",richTextBox1.Lines);
but this code save whole of data in .txt file and is not controllable.
this is that part of code on richtextbox2:
public void detectFingers(Leap.Frame frame)
{
foreach(Finger finger in frame.Fingers)
{
richTextBox2.AppendText("Finger ID: " + finger.Id + Environment.NewLine +
"Finger Type: " + finger.Type + Environment.NewLine +
"Finger Length:" + finger.Length + Environment.NewLine +
"Finger width:" + finger.Width + Environment.NewLine);
foreach (Bone.BoneType boneType in (Bone.BoneType[])Enum.GetValues(typeof(Bone.BoneType)))
{
Bone bone = finger.Bone(boneType);
richTextBox3.AppendText("Bone Type: " + bone.Type +Environment.NewLine +
"Bone Length: " +bone.Length +Environment.NewLine+
"Bone Width : " + bone.Width +Environment.NewLine +
"Previous Joint : "+bone.PrevJoint + Environment.NewLine+
"Next Joint :" + bone.NextJoint + Environment.NewLine+
"Direction : " + bone.Direction + Environment.NewLine+;
}
}
}

As data comes in continuously you need to save from when the data should be stored uptil when. Printing the textBox1.Text will, of course, print everything.
You need to set a variable to store the information after the "Start" button is pressed until the "Stop" button is pressed. Here is some code:
private bool isLogging = false;
private string myLog = "";
//This is where the input from the sensor arrives
private void myInput(string s)
{
textBox1.Text += s + "\n";
if (isLogging)
myLog += s + "\n";
}
private void buttonOnStart_Click(object sender, EventArgs e)
{
//Clear log string
myLog = "";
//Start logging
isLogging = true;
}
private void buttonOnStop_Click(object sender, EventArgs e)
{
//Stop logging
isLogging = false;
//Pring only the logged messages
System.IO.File.WriteAllLines(#"C:\Users\Mohammad_Taghi\Desktop\a.txt", myLog);
}

Related

How to fix issue of zkemkeeper.dll realtime events inside windows service?

i'm setting up windows service and want it to sync the device attendance to SQL Server database using zkemkeeper real time event. i have successfully created service as well as tested the service on my local system which run windows 10 and another one window 8 service work fine and sync the attendance record to DB server at real time. Now after successful testing on local system i deployed service over production server where service successfully established the connection with device but it didn't respond to Real time event for testing purpose i have created winform app and run it over the server and find out it is working and listening to real time event but i need service to work properly not win form application any help will be appreciated thanks below is my code !
public partial class AttendanceSyncService_405 : ServiceBase
{
public AttendanceSyncService_405()
{
InitializeComponent();
}
System.Timers.Timer timer = new System.Timers.Timer();
public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
private bool bIsConnected = false;//the boolean value identifies whether the device is connected
private int iMachineNumber = 1;//the serial number of the device.After connecting the device ,this value will be changed.
protected override void OnStart(string[] args)
{
//var thread = new Thread();
//thread.SetApartmentState(ApartmentState.STA);
//thread.Start();
WriteToFile("Service is started at " + DateTime.Now);
Connect();
// LoadCurrentMonthAtt();
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 900000; //number in milisecinds
timer.Enabled = true;
}
protected override void OnStop()
{
WriteToFile("Service is stopped at " + DateTime.Now);
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
if (bIsConnected == true)
{
WriteToFile("Service recall at " + DateTime.Now);
WriteToFile("Device Status Connected at " + DateTime.Now);
}
else
{
WriteToFile("Device Status DisConnected at " + DateTime.Now);
WriteToFile("Service recall at " + DateTime.Now);
Connect();
}
}
public void WriteToFile(string Message)
{
string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(Message);
}
}
else
{
using (StreamWriter sw = File.AppendText(filepath))
{
sw.WriteLine(Message);
}
}
}
private void Connect()
{
try
{
int idwErrorCode = 0;
bIsConnected = axCZKEM1.Connect_Net("192.168.0.177", 4370);
if (bIsConnected == true)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
iMachineNumber = 1;
if (axCZKEM1.RegEvent(iMachineNumber, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
}
else
{
WriteToFile("RT Events didn't registered at " + DateTime.Now);
}
axCZKEM1.RegEvent(iMachineNumber, 65535);//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
WriteToFile("Device Connection Established Successfully at " + DateTime.Now);
}
else
{
axCZKEM1.GetLastError(ref idwErrorCode);
WriteToFile("Unable to connect the device,ErrorCode=" + idwErrorCode.ToString() + " at " + DateTime.Now);
}
}
catch(Exception ex)
{
WriteToFile("Exception :" + ex.Message + " at " + DateTime.Now);
}
}
private void axCZKEM1_OnAttTransactionEx(string sEnrollNumber, int iIsInValid, int iAttState, int iVerifyMethod, int iYear, int iMonth, int iDay, int iHour, int iMinute, int iSecond, int iWorkCode)
{
DateTime Attendancedate = new DateTime(iYear, iMonth, iDay, iHour, iMinute, iSecond);
string row = sEnrollNumber + "," + Attendancedate.ToString();
WriteToFile("Attendane :" + row + " Marked At: " + DateTime.Now);
if (bIsConnected == false)
{
Connect();
return;
}
decimal empserial = decimal.Parse(sEnrollNumber);
attInsert(empserial, Attendancedate);
}
private void attInsert(decimal empserial, DateTime Attendancedate)
{
try
{
WriteToFile("Attendance Entry Arrived for EMP-Serial :" + empserial + " At: " + DateTime.Now + " for Insertion");
DBAccess db = new DBAccess();
DataSet attCount = db.GetDataSetFromQuery("select Count(att.[todayCount]) as attCount from tblAttendance att where (att.attDate = Convert(date,GETDATE()) AND att.fkSerial ='" + empserial.ToString() + "')");
int count = int.Parse(attCount.Tables[0].Rows[0]["attCount"].ToString());
Boolean INOUT = (count % 2 == 0) ? true : false;
WriteToFile("Attendane Count :" + count + " & In/Out : " + INOUT + " Marked At: " + DateTime.Now);
db.Parameters.AddWithValue("fkSerial", empserial);
db.Parameters.AddWithValue("attTerminalId", "Time1");
db.Parameters.AddWithValue("attDateTime", Attendancedate);
db.Parameters.AddWithValue("attTgId", 3);
db.Parameters.AddWithValue("attINOUT", INOUT);
db.Parameters.AddWithValue("attEmpCode", "no need");
db.ExecuteNonQuery("spInsertAttendance");
WriteToFile("Attendance Inserted of EMP-Serial :" + empserial + " At: " + DateTime.Now);
}
catch (Exception ex)
{
WriteToFile("Exception in insert method :" + ex.Message + " At: " + DateTime.Now);
}
}
}
Type This Code in Your IntializeComponent and it will respond to realtime events
private void InitializeComponent()
{
Thread createComAndMessagePumpThread = new Thread(() =>
{
axCZKEM1 = new zkemkeeper.CZKEMClass();
bool connSatus = axCZKEM1.Connect_Net(192.168.0.177, 4370);
if (connSatus == true)
{
this.axCZKEM1.OnAttTransactionEx -= new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
if (axCZKEM1.RegEvent(1, 65535))//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
{
this.axCZKEM1.OnAttTransactionEx += new zkemkeeper._IZKEMEvents_OnAttTransactionExEventHandler(axCZKEM1_OnAttTransactionEx);
}
}
Application.Run();
});
createComAndMessagePumpThread.SetApartmentState(ApartmentState.STA);
createComAndMessagePumpThread.Start();
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}

CrossGeolocator GetPositionAsync exits loop/method

I want to keep the phone's location quite often in an App, so I'm using the GetPositionAsync method, and keep calling that. I've written some code, and when I attach that in a simple OnAppearing method everything works fine. If I write it in a method or while loop, when it gets to the GetPositionAsync or some other local database things, I think only awaitable methods, it goes right out of the loop/method. I am using async. Any ideas?
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 20;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
location.Latitude = position.Latitude;
location.Longitude = position.Longitude;
await App.LocationDatabase.SaveLocationAsync(location);
await Task.Delay(TimeSpan.FromSeconds(10));
You're not sharing any loop code, so it's hard to reproduce your issue.
Anyway, you shouldn't call GetPositionAsync in a loop, use the StartListeningAsync method and connect to the PositionChange event instead.
async Task StartListeningAsync()
{
if(CrossGeolocator.Current.IsListening)
return;
await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(5), 10, true);
CrossGeolocator.Current.PositionChanged += PositionChanged;
CrossGeolocator.Current.PositionError += PositionError;
}
private void PositionChanged(object sender, PositionEventArgs e)
{
//If updating the UI, ensure you invoke on main thread
var position = e.Position;
var output = "Full: Lat: " + position.Latitude + " Long: " + position.Longitude;
output += "\n" + $"Time: {position.Timestamp}";
output += "\n" + $"Heading: {position.Heading}";
output += "\n" + $"Speed: {position.Speed}";
output += "\n" + $"Accuracy: {position.Accuracy}";
output += "\n" + $"Altitude: {position.Altitude}";
output += "\n" + $"Altitude Accuracy: {position.AltitudeAccuracy}";
Debug.WriteLine(output);
}
private void PositionError(object sender, PositionErrorEventArgs e)
{
Debug.WriteLine(e.Error);
//Handle event here for errors
}
async Task StopListeningAsync()
{
if(!CrossGeolocator.Current.IsListening)
return;
await CrossGeolocator.Current.StopListeningAsync();
CrossGeolocator.Current.PositionChanged -= PositionChanged;
CrossGeolocator.Current.PositionError -= PositionError;
}
https://jamesmontemagno.github.io/GeolocatorPlugin/LocationChanges.html

How to get the newly opened apps WPF

Is there any way to get the newly open apps? I have a function that gets the running apps every 10 seconds, place them on a listbox and sends them to the other window if you click the send button.
What I wanted to happen is to get the newly opened app and send it to the other window. For example:
for the first 10 secs, I have opened notepad and chrome, after clicking send, those two will be sent to the other window. For the next 10 secs, I opened another app which is firefox. So my opened apps are now notepad, chrome and firefox so when I click send, I only want firefox to be sent to the other window so it wouldn't be redundant. Is this even possible?
There's the codes, in case if it brings of any help.
private void SendData()
{
String processID = "";
String processName = "";
String processFileName = "";
String processPath = "";
string hostName = System.Net.Dns.GetHostName();
listBox1.BeginUpdate();
try
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
piis = GetAllProcessInfos();
try
{
processID = piis[i].Id.ToString();
processName = piis[i].Name.ToString();
processFileName = piis[i].FileName.ToString();
processPath = piis[i].Path.ToString();
output.Text += "\n\nSENT DATA : \n\t" + processID + "\n\t" + processName + "\n\t" + processFileName + "\n\t" + processPath + "\n";
}
catch (Exception ex)
{
wait.Abort();
output.Text += "Error..... " + ex.StackTrace;
}
NetworkStream ns = tcpclnt.GetStream();
String data = "";
data = "--++" + " " + processID + " " + processPath + " " + processFileName + " " + hostName;
if (ns.CanWrite)
{
byte[] bf = new ASCIIEncoding().GetBytes(data);
ns.Write(bf, 0, bf.Length);
ns.Flush();
}
}
}
finally
{
listBox1.EndUpdate();
}
}
Store the Id of previously sent processes in a list and only send the process info of a process if it's id is not in the list.
private List<int> listedProcesses = new List<int>();
//...
try
{
if(!listedProcesses.Contains(piis[i].Id)
{
listedProcesses.Add(piis[i].Id);
processID = piis[i].Id.ToString();
processName = piis[i].Name.ToString();
processFileName = piis[i].FileName.ToString();
processPath = piis[i].Path.ToString();
output.Text += "\n\nSENT DATA : \n\t" + processID + "\n\t" + processName + "\n\t" + processFileName + "\n\t" + processPath + "\n";
}
}
//...
Also: when you close processes these two lines will no longer be valid:
for (int i = 0; i < listBox1.Items.Count; i++)
{
piis = GetAllProcessInfos();
Because the number of processes can now be lower than the number of items in the listbox.
To keep them in sync you will also have to remove items from the listbox when processes are closed.
To fix it even more efficient (and easier) you could simply clear the listbox and add a new item for each process returned by GetAllProcessInfos();
Have a hook as described here: How to hook into application and process startup in windows?
using System.Management;
// Run this in another thread and make sure you dispose the event watcher before exit
var start = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
start.EventArrived += new EventArrivedEventHandler(delegate (object sender, EventArrivedEventArgs e) {
console.WriteLine("Name: {0}, Command Line: {1}", e.NewEvent.Properties["ProcessName"].Value, e.NewEvent.Properties["Commandline"].Value);
});
start.Start()

Entering information into database with visual studio form

I am encountering a problem when I attempt to enter information into a database that is connected to my visual studio 2012 form. When I start debugging if I enter information into the fields and hit submit, nothing gets entered into my database. If I enter the information again and hit submit, the information then will write to my database. I am not really great at programming, so I used the data sources to link my visual studio form and my database.
This is what my form looks like;
data form before entry
This is what my form looks like with data I enter;
data form with information
This is what happens when you hit submit;
confirmation message
This is the database after hitting submit the first time; db entries after first submission
This is what happens when I enter the information again; db entries after second submission
Any entries after this will enter correctly, and things are great. I am confused as to why information (besides the null entry) wont enter until the second time I click submit. While it "technically works" it's not quite right. Any help on the issue would be much appreciated.
Here is my code for my submit button in my New Customer Form;
namespace WindowsFormsApplication2
{
public partial class frmNewCustomer : Form
{
public frmNewCustomer()
{
InitializeComponent();
}
private void btnAddCustomer_Click(object sender, EventArgs e)
{
string cstFName;
string cstLName;
string cstAddress;
string cstCity;
string cstState;
string cstZip;
string cstPhone;
string cstEmail;
cstFName = cstFNameTxtBox.Text;
cstLName = cstLNameTxtBox.Text;
cstAddress = cstAddressTxtBox.Text;
cstCity = cstCityTxtBox.Text;
cstState = cstStateTxtBox.Text;
cstZip = cstZipTxtBox.Text;
cstPhone = cstPhoneTxtBox.Text;
cstEmail = cstEmailTxtBox.Text;
// exception handler for empty fields
if (cstFName == "")
{
MessageBox.Show("Please enter your first name!");
}
else if (cstLName == "")
{
MessageBox.Show("Please enter your last name!");
}
else if (cstAddress == "")
{
MessageBox.Show("Please enter your address!");
}
else if (cstCity == "")
{
MessageBox.Show("Please enter your city!");
}
else if (cstState == "")
{
MessageBox.Show("Please enter your state!");
}
else if (cstZip == "")
{
MessageBox.Show("Please enter your zip!");
}
else if (cstPhone == "")
{
MessageBox.Show("Please enter your Phone!");
}
else if (cstEmail == "")
{
MessageBox.Show("Please enter your email!");
}
else
{
MessageBox.Show("First Name: " + cstFName + " Last Name: " + cstLName + "\r\n" +
"Address: " + cstAddress + "\r\n" +
"City: " + cstCity + " State: " + cstState + " Zip: " + cstZip + "\r\n" +
"Phone: " + cstPhone + " Email: " + cstEmail + "\r\n" + "\r\n" +
"Has been added to the database.");
}
this.tblCustomersBindingSource.AddNew();
this.tblCustomersBindingSource.EndEdit();
this.tblCustomersTableAdapter.Update(this.dataSet1.tblCustomers); // Updating the DB Table
}
private void frmNewCustomer_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dataSet1.tblCustomers' table. You can move, or remove it, as needed. Loads it into start of form!
// this.tblCustomersTableAdapter.Fill(this.dataSet1.tblCustomers);
}
}
}
I realize my exception handling is janky at best, but this is more about creating a few forms that read and write data to a db. I appreciate any help anyone is able to offer,
If this weren't winforms (not sure that it matters), the typical flow is this:
Create a connection.
Write your insert statement.
Do data validation.
Submit to database.
Commit transaction.
try this:
bool shouldSubmit = false;
// exception handler for empty fields
if (cstFName == "")
{
MessageBox.Show("Please enter your first name!");
}
else if (cstLName == "")
{
MessageBox.Show("Please enter your last name!");
}
else if (cstAddress == "")
{
MessageBox.Show("Please enter your address!");
}
else if (cstCity == "")
{
MessageBox.Show("Please enter your city!");
}
else if (cstState == "")
{
MessageBox.Show("Please enter your state!");
}
else if (cstZip == "")
{
MessageBox.Show("Please enter your zip!");
}
else if (cstPhone == "")
{
MessageBox.Show("Please enter your Phone!");
}
else if (cstEmail == "")
{
MessageBox.Show("Please enter your email!");
}
else
{
shouldSubmit = true;
MessageBox.Show("First Name: " + cstFName + " Last Name: " + cstLName + "\r\n" +
"Address: " + cstAddress + "\r\n" +
"City: " + cstCity + " State: " + cstState + " Zip: " + cstZip + "\r\n" +
"Phone: " + cstPhone + " Email: " + cstEmail + "\r\n" + "\r\n" +
"Has been added to the database.");
}
if(shouldSubmit)
{
this.tblCustomersBindingSource.AddNew();
this.tblCustomersBindingSource.EndEdit();
this.tblCustomersTableAdapter.Update(this.dataSet1.tblCustomers); // Updating the DB Table
}

Why does program lag and freeze while starting process?

I have a code that is supposed to start a process in order to render animation. It works great and starts the process and all, but while the process is running, my program says not responding, and freezes refusing to update progress at all.
Here is the code that should be causing the issue:
void Render()
{
while (currentFrame <= lastFrame)
{
bool rendering = IsRendering("cmd");
if (rendering == false)
{
StreamWriter renderBatch = new StreamWriter(batchFile);
renderBatch.Write('"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"');
renderBatch.Close();
var renderProcess = new Process();
renderProcess.StartInfo = new ProcessStartInfo(batchFile);
//renderProcess.StartInfo.Arguments = '"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"';
renderProcess.StartInfo.UseShellExecute = false;
//renderProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
renderProcess.Start();
if (renderProcess.HasExited == true && currentFrame < lastFrame)
{
ProgressBar1.Value = (currentFrame - 1) / lastFrame;
currentFrame++; //goes onto the next frame once it is done rendering this frame
}
}
}
}
Here is the full code that it is in:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//using System.Net;
using System.Diagnostics;
using System.IO;
namespace Maya_Network_Render
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Globals ///////////////////////////////////////
string prefFile = "C:\\Program Files\\Maya Render Buddy Preferences\\options.txt";
string batchFile = "C:\\Program Files\\Maya Render Buddy Preferences\\render.bat";
int firstFrame;
int lastFrame;
int currentFrame;
// Globals //////////////////////////////////////
private void Form1_Load(object sender, EventArgs e)
{
if (Directory.Exists("C:\\Program Files\\Maya Render Buddy Preferences"))
{
if (File.Exists(prefFile))
{
StreamReader preferences = new StreamReader(prefFile);
string renderFilePath = preferences.ReadLine();
renderPathField.Text = renderFilePath;
preferences.Close();
}
else
{
File.Create(prefFile);
}
}
else
{
Directory.CreateDirectory("C:\\Program Files\\Maya Render Buddy Preferences");
File.Create(prefFile);
}
}
private void sceneBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog scenefinder = new OpenFileDialog();
scenefinder.Title = "Browse to your Maya scene file";
scenefinder.RestoreDirectory = true;
if (scenefinder.ShowDialog() == DialogResult.OK)
{
sceneFile.Text = scenefinder.FileName;
}
}
private void imageBrowse_Click(object sender, EventArgs e)
{
FolderBrowserDialog imageFolderSelection = new FolderBrowserDialog();
imageFolderSelection.ShowDialog();
imagePath.Text = imageFolderSelection.SelectedPath;
}
private void renderButton_Click(object sender, EventArgs e)
{
string imageSavePath = imagePath.Text;
string scene = sceneFile.Text;
try
{
if (FirstFrameTextbox.Text != "" && LastFrameTextBox.Text != "") // if the textboxes are filled in then assign them to a variable
{
firstFrame = Convert.ToInt32(FirstFrameTextbox.Text);
lastFrame = Convert.ToInt32(LastFrameTextBox.Text);
if (File.Exists(scene))
{
if (File.Exists(batchFile))
{
currentFrame = firstFrame;
progressMessage.Text = " Rendering Frame " + currentFrame + " of " + lastFrame + " from " + scene;
Render();
}
else
{
File.Create(batchFile); // if there is no batch file then we make one!
currentFrame = firstFrame;
progressMessage.Text = " Rendering Frame " + currentFrame + " of " + lastFrame + " from " + scene;
Render();
}
}
else // if there is not a scene file we let the user know that
{
MessageBox.Show("Please fill in image path, project path and scene file", "Cannot find file");
progressMessage.Text = " ERROR! SCENE FILE OR IMAGE PATH IS MISSING";
}
}
else
{
MessageBox.Show("The numbers entered into the first or last frame fields are invalid", "invalid frame range");
}
}
catch (Exception f)
{
MessageBox.Show(f.ToString() + " Most commonly errors result non numerical input in the frame entry fields", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void ChangeRenderPath_Click(object sender, EventArgs e)
{
OpenFileDialog renderfinder = new OpenFileDialog();
renderfinder.Title = "Browse to your Render.exe file";
renderfinder.RestoreDirectory = true;
if (renderfinder.ShowDialog() == DialogResult.OK)
{
StreamWriter preferences = new StreamWriter(prefFile);
renderPathField.Text = renderfinder.FileName;
preferences.Write(renderPathField.Text);
preferences.Close();
}
}
public bool IsRendering(string processName)
{
foreach (Process renderProcess in Process.GetProcesses())
{
if (renderProcess.ProcessName.Contains(processName))
{
return true;
}
}
return false;
}
void Render()
{
while (currentFrame <= lastFrame)
{
bool rendering = IsRendering("cmd");
if (rendering == false)
{
StreamWriter renderBatch = new StreamWriter(batchFile);
renderBatch.Write('"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"');
renderBatch.Close();
var renderProcess = new Process();
renderProcess.StartInfo = new ProcessStartInfo(batchFile);
//renderProcess.StartInfo.Arguments = '"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"';
renderProcess.StartInfo.UseShellExecute = false;
//renderProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
renderProcess.Start();
if (renderProcess.HasExited == true && currentFrame < lastFrame)
{
ProgressBar1.Value = (currentFrame - 1) / lastFrame;
currentFrame++; //goes onto the next frame once it is done rendering this frame
}
}
}
}
private void Form1_FormClosing_1(object sender, FormClosingEventArgs e)
{
if (DialogResult.No == MessageBox.Show("If this program is not open it will not assign renders. Would you still like to close?", "You are about to stop rendering!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation))
{
e.Cancel = true;
}
else
{
foreach (Process renderProcess in Process.GetProcesses())
{
if (renderProcess.ProcessName.Contains("cmd"))
{
renderProcess.Kill();
}
}
}
}
} // form closing brace
}
UI updates need to happen on a different thread than the main process, otherwise it will wait until the entire process is complete before showing you the updated UI.
Since you have a lot of "process" code inside your form there's not a simple fix - you will need to start the processing in another thread and set up events to pass updates back to the UI.

Categories