|
You need to have a look at the invoke methods in the article shown by the other poster
MSDN: Look at the example at the bottom of the page[^]
As barmey as a sack of badgers
Dude, if I knew what I was doing in life, I'd be rich, retired, dating a supermodel and laughing at the rest of you from the sidelines.
|
|
|
|
|
This[^] explains it, however all examples are C# or VB.NET; same principles apply to C++/CLI.
Amd a BackgroundWorker's ProgressChanged and RunWorkerCompleted handlers don't have the cross-thread problem as they run on the thread that created the BGW, which normally is the main thread. That is one of the big advantages of BGW.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
I have a windows Forms application that calls a mathematical calculations .exe
superMinerProcess->Start();
superMinerProcess->BeginOutputReadLine();
while (!superMinerProcess->HasExited)
{
If I set a breakpoint after the Start(); the program only reaches it after the process has finished. I don't understand... Any idea?
|
|
|
|
|
That is inconclusive. Where is this code located? what is in the while loop? what is it you are trying to achieve?
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
The application is a dialog that runs a long mathematical calculation (the external process, an independent executable) when pressing a Run button. Hence, this code is located within the buttonRun_Click function.
while (!superMinerProcess->HasExited)
{
if (processCancelled)
{
processCancelled = false;
break;
}
}
processCancelled is set to true in buttonCancel_Click . What I´m trying is to be able to kill the process when the user clicks on the Cancel button. I´ve tried writing superMinerProcess->Kill() in buttonCancel_Click but it won´t work because the Cancel button is just not clickable while the process is running.
Here´s the rest of relevant code of the process
superMinerProcess = gcnew System::Diagnostics::Process;
superMinerProcess->StartInfo = gcnew System::Diagnostics::ProcessStartInfo;
superMinerProcess->StartInfo->RedirectStandardOutput = true;
superMinerProcess->StartInfo->UseShellExecute = false;
superMinerProcess->StartInfo->FileName = SUPERMINER_EXE;
superMinerProcess->StartInfo->CreateNoWindow = true;
superMinerProcess->StartInfo->Arguments = getArguments();
superMinerProcess->OutputDataReceived += gcnew System::Diagnostics::DataReceivedEventHandler (&Form1::StdoutHandler);
|
|
|
|
|
OK, that is quite wrong for several reasons:
1.
the while loop has no blocking calls, so it will spin at full speed, consuming all cycles of one (perhaps the only) core. If you must have a polling loop like that, at least slow it down by inserting say Thread.Sleep(100);
However it is in general better to avoid a polling loop.
2.
It is not OK to halt the main thread like that, as the whole GUI will freeze. If e.g. another window pops up on top of your app, and then goes away again, your app won't repaint itself.
The correct approach would be:
- to have a separate thread (I suggest a BackgroundWorker) which launches the process, captures its output, and waits for its termination;
- to launch this thread from your button click handler (possibly also disabling said button, turning the cursor into a wait cursor, etc);
- to have a delegate dealing with intermediate results (maybe showing them in a ListBox);
- to have another delegate dealing with the termination of the process (restoring the GUI back to normal).
BTW: said thread would not need a polling loop on superMinerProcess->HasExited , as it could use superMinerProcess->WaitForExit()
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
I like the idea of having the process in a different thread. It does work much better.
However I have a problem when it comes to display in my form the text captured from the process. I have a delegate superMinerThreadWorkCompleted in charge of displaying the results.
void superMinerThreadWorkCompleted (System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e)
{
textBox = "Process text";
}
But I get the error
C3352: superMinerThreadWorkCompleted(System::Object ^,System::ComponentModel::DoWorkEventArgs ^)' : the specified function does not match the delegate type 'void (System::Object ^,System::ComponentModel::RunWorkerCompletedEventArgs ^)'<br />
1>Form1.cpp in the line
superMinerThread->RunWorkerCompleted += gcnew System::ComponentModel::RunWorkerCompletedEventHandler (&Form1::superMinerThreadWorkCompleted);
I can fix this by making the delegate static but then I cannot modify member class textBox .
What could be the way around this?
|
|
|
|
|
piul wrote: DoWorkEventArgs
piul wrote: RunWorkerCompletedEventArgs
these are different! the former is just wrong.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
Changed the delegate to
void superMinerThreadWorkCompleted (System::Object^ sender,
System::ComponentModel::RunWorkerCompletedEventArgs^ e)
{}
and still got the same error
'void SuperMinerGUI::Form1::superMinerThreadWorkCompleted(System::Object ^,System::ComponentModel::RunWorkerCompletedEventArgs ^)' : the specified function does not match the delegate type 'void (System::Object ^,System::ComponentModel::RunWorkerCompletedEventArgs ^)'<br />
1>Form1.cpp
|
|
|
|
|
for non-static (instance) delegates, you need a constructor that takes two arguments, the first being this .
superMinerThread->RunWorkerCompleted += gcnew System::ComponentModel::RunWorkerCompletedEventHandler
(this, &Form1::superMinerThreadWorkCompleted);
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
|
I have 2 classes both of which are not trying to call a userform but I keep getting this error:
<br />
An error occurred creating the form. See Exception.InnerException for details. The error is: The form referred to itself during construction from a default instance, which led to infinite recursion. Within the Form's constructor refer to the form using 'Me.'<br />
This is the code to my form1:
Public Class Form1
Dim getwmi As New wmiget()
Dim smtp As New smtp()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
getwmi.Main()
End Sub
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
tbAt.Clear()
FindAttachment.Title = "Please select a file"
FindAttachment.InitialDirectory = Environment.GetEnvironmentVariable("userprofile") + "\Desktop"
FindAttachment.ShowDialog()
End Sub
Private Sub FindAttachment_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles FindAttachment.FileOk
Dim filepath As System.IO.FileStream = FindAttachment.OpenFile()
tbAt.Text = FindAttachment.FileName.ToString.ToLower()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
tbTo.Clear()
tbFr.Clear()
tbSu.Clear()
tbBo.Clear()
tbSe.Clear()
tbAt.Clear()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If tbUs.Text = "" And tbPa.Text = "" Then
MsgBox("Smtp:[" + tbSe.Text + "]: requires a username and password to continue")
End If
smtp.smtp()
End Sub
End Class
This is the code to my smtp class:
Imports System.Net.Mail
Public Class smtp
Dim username As String = Form1.tbUs.Text
Dim password As String = Form1.tbPa.Text
Public Sub smtp()
Try
'Start by creating a mail message object
Dim MyMailMessage As New MailMessage()
'From requires an instance of the MailAddress type
MyMailMessage.From = New MailAddress(Form1.tbFr.Text.ToLower())
'To is a collection of MailAddress types
MyMailMessage.To.Add(Form1.tbTo.Text.ToLower())
MyMailMessage.Subject = Form1.tbSu.Text
MyMailMessage.Body = Form1.tbBo.Text
'Add attachment
Dim attachFile As New Attachment(Form1.tbAt.Text)
MyMailMessage.Attachments.Add(attachFile)
'Create the SMTPClient object and specify the SMTP server
Dim SMTPServer As New SmtpClient(Form1.tbSe.Text.ToLower())
SMTPServer.Port = 587
SMTPServer.Credentials = New System.Net.NetworkCredential(username, password)
SMTPServer.EnableSsl = True
Try
SMTPServer.Send(MyMailMessage)
MsgBox("Email Sent Successfully.", vbInformation, "Email Notification")
username = ""
password = ""
Catch ex As SmtpException
MessageBox.Show(ex.Message)
End Try
Catch EX As Exception
MessageBox.Show(EX.Message)
End Try
End Sub
End Class
And this is the code to which my error is pointing to:
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.1
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
' or if you encounter build errors in this file, go to the Project Designer
' (go to Project Properties or double-click the My Project node in
' Solution Explorer), and make changes on the Application tab.
'
Partial Friend Class MyApplication
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Public Sub New()
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.TeamSpec.Form1
End Sub
End Class
End Namespace
I cant seem to revert my changes and get rid of the error, i mean i have reverted the changes but its still throwing it at me.
|
|
|
|
|
Without running your code in Visual Studio, hit F10 to step through the code line by line until you get back to a part where you already were.
The piece you're not showing is the getwmi class and its main method. I have a feeling you're making a reference to Form1 in there somewhere.
|
|
|
|
|
Herboren wrote: And this is the code to which my error is pointing to:
An expception points to a single line, which line is it?
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
There is so much wrong with your code...
1. Too many End Sub
2. Needs more open/close braces
3. Needs more semi-colons
4. As should be replaced with an equals symbol (=)
...fix this and then we can talk
Illogical thoughts make me ill
|
|
|
|
|
Why did you feel the need to post this?
A total waste of everybody's time, including your own.
Henry Minute
Do not read medical books! You could die of a misprint. - Mark Twain
Girl: (staring) "Why do you need an icy cucumber?"
“I want to report a fraud. The government is lying to us all.”
I wouldn't let CG touch my Abacus!
When you're wrestling a gorilla, you don't stop when you're tired, you stop when the gorilla is.
|
|
|
|
|
WARNING: THE FOLLOWING CONTENT IS MOSTLY FOR PURPOSES OF HUMOUR. IF YOU CANNOT HANDLE A JOKE THEN PLEASE DO NOT CONTINUE TO READ THIS MESSAGE FOR FEAR OF YOUR TIME BEING WASTED
Henry Minute wrote: Why did you feel the need to post this?
Because I don't live in a world where everything has to be serious. Perhaps a different world to your own - but I imagine some higher power permits my way of thinking, hence the 'Joke' message type.
Henry Minute wrote: A total waste of everybody's time, including your own.
I would hardly say everybody's time, in fact, nearly all the people I know (and I'm talking double figures here) wont waste any time over this post. But you are not completely wrong, I am wasting my time, so I thank you for wasting your own to put me back on the righteous path again.
I apologise to any viewers without a sense of humour but I am sure if you direct a letter of complaint to my Country then I will be forced to offer an official world-wide apology... may I never see the funny side of anything again for the rest of my life.
Illogical thoughts make me ill
|
|
|
|
|
I have no problem with humour at all but in it's proper place.
If you had posted that message to one of the answerers, I would have no problem with it. I might even have upvoted it, I enjoy poking VB with a stick too.
Posting it to someone asking for help is the wrong thing to do, unless they are an obvious troll.
Henry Minute
Do not read medical books! You could die of a misprint. - Mark Twain
Girl: (staring) "Why do you need an icy cucumber?"
“I want to report a fraud. The government is lying to us all.”
I wouldn't let CG touch my Abacus!
When you're wrestling a gorilla, you don't stop when you're tired, you stop when the gorilla is.
|
|
|
|
|
well... you almost half have a point so I will accept defeat and take this as a lesson learned.
Man this is turning out to be an exhaustive day after all
Illogical thoughts make me ill
|
|
|
|
|
Hi, I have a requirment that allows user to insert new records at the end of the footer.
My database table contains all these:
termsID int
terms varchar
defaultValue varchar
actualValue varchar
reasonForDeviation varchar
alert varchar
contractID varchar
In one of the column, known as Alert, it is a hyperlink such that user is able to click on the 'Set Alert' hyperlink and it will becomes an alert icon. After all the necessary into such as: Terms, Default value, Actual Value, Reason For deviation, alert(set hyperlink) and contract ID is filled in. User is able to click on the Add New link to set the it to become an alert icon.After the records is inserted, user is able to view the details and in the alert columnm, the hyperlink is changed to an alert icon. I am not sure of how to code out for it. This is my business logic:
protected void gvCriticalTerms_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtTerms = (TextBox)gvCriticalTerms.FooterRow.FindControl("txtTerms");
TextBox txtDefaultValue = (TextBox)gvCriticalTerms.FooterRow.FindControl("txtDefaultValue");
TextBox txtActualValue = (TextBox)gvCriticalTerms.FooterRow.FindControl("txtActualValue");
TextBox txtReasonForDeviation = (TextBox)gvCriticalTerms.FooterRow.FindControl("txtReasonForDeviation");
TextBox txtAlert = (TextBox)gvCriticalTerms.FooterRow.FindControl("txtAlert");
TextBox txtContractID = (TextBox)gvCriticalTerms.FooterRow.FindControl("txtContractID");
vrmdb.Insert_CriticalTermsRecords(txtTerms.Text, txtDefaultValue.Text, txtActualValue.Text, txtReasonForDeviation.Text, txtAlert.Text, txtContractID.Text);
BindGrid();
Response.Redirect("ContractThreeGridView.aspx");
}
}
Thanks!Hope to hear from u soon!
|
|
|
|
|
Hello,
I am writing a program which transfers music files to devices like iPod and other mp3/music player. I am done with iPod, I use ITunes library for that and able to list and sync music in device. I could find Apple device using WMI query,
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "Select * from Win32_PnPEntity Where Name Like '%Apple%'");
But I am not able to do it with other devices. Problem is I am not finding any WMI query to detect weather device is music player or portable device. I wanted to use Windows Media Player for Sync music files to music player.
Any help is appropriated.
Thanks in advance
|
|
|
|
|
You already posted this in the C# forum; please post in one forum only.
I must get a clever new signature for 2011.
|
|
|
|
|
Hi All,
Is there a way to read the Timeout value from the web.config file within JavaScript?
Thank you,
Mel
|
|
|
|
|
The web.config file is restricted by the ASP.NET engine and is not available from client-side script or from directly browsing for it.
I know the language. I've read a book. - _Madmatt
|
|
|
|
|
Thank you for your reply Mark.
Should I therefore be able to store the timeout in to a C# variable and then access that variable in JavaScript?
I'm unable to carryout the following at the moment:
1. Access the timeout value from the web.config file in C#
2. Access a C# variable in JavaScript.
Any ideas on how I can do this?
For #2 I thought the following shoudl work:
C# code:
public string strTest = "Test String";
JavaScript:
alert('<%=strTest%>');
However, the alert box prints out the text "<%=strTest%>".
Any ideas?
Thank you
|
|
|
|