|
This can be done by creating custom events on your form that has the ProgressBar and wraps a BackgroundWorker.
I have my own custom class that I use for this which I am intending to post in an article real soon but here is the code if it helps - it is using a custom progress bar that has a Marquee property rather than Style, but the calls to this can easily be altered to use the standard one. The worker part of this code is essentially the same as the .NET BackgroundWorker and I have extended the ProgressChangedEventArgs so I can pass two lots of text in addition to the usual.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
namespace DaveyM69.Windows.Forms
{
[ToolboxBitmap(typeof(Form))]
public class ProgressForm : Form
{
public const string NoMessageChange = null;
public const int NoProgressChange = -1;
public event DoWorkEventHandler DoWork;
public event ProgressChangedEventHandler ProgressChanged;
public event RunWorkerCompletedEventHandler RunWorkerCompleted;
private object argument;
private AsyncOperation asyncOperation;
private Button button;
private bool cancellationPending;
private readonly SendOrPostCallback completed;
private bool isBusy;
private Label label;
private readonly SendOrPostCallback progress;
private ProgressBar progressBar;
private readonly ParameterizedThreadStart work;
private bool workerReportsProgress;
private bool workerSupportsCancellation;
public ProgressForm()
{
InitializeComponent();
argument = null;
asyncOperation = null;
completed = new SendOrPostCallback(Completed);
isBusy = false;
progress = new SendOrPostCallback(Progress);
work = new ParameterizedThreadStart(Work);
workerReportsProgress = true;
workerSupportsCancellation = true;
}
[Browsable(false)]
public object Argument
{
get { return argument; }
set
{
if (argument != value)
{
if (!isBusy)
argument = value;
}
}
}
[Browsable(false)]
public bool CancellationPending
{
get { return cancellationPending; }
}
[Browsable(false)]
public bool IsBusy
{
get { return isBusy; }
}
[DefaultValue(true)]
public bool WorkerReportsProgress
{
get { return workerReportsProgress; }
set
{
if (workerReportsProgress != value)
{
workerReportsProgress = value;
SetWorkerReportsProgress();
}
}
}
[DefaultValue(true)]
public bool WorkerSupportsCancellation
{
get { return workerSupportsCancellation; }
set
{
if (workerSupportsCancellation != value)
{
workerSupportsCancellation = value;
SetWorkerSupportsCancellation();
}
}
}
public void CancelAsync()
{
if (isBusy)
{
button.Enabled = false;
cancellationPending = true;
}
}
private void Completed(object state)
{
asyncOperation = null;
cancellationPending = false;
isBusy = false;
button.Enabled = false;
RunWorkerCompletedEventArgs e = (RunWorkerCompletedEventArgs)state;
OnRunWorkerCompleted(e);
if (Modal)
DialogResult = e.Cancelled ?
DialogResult.Cancel : e.Error == null ?
DialogResult.OK : DialogResult.Abort;
else
Close();
}
private void InitializeComponent()
{
this.label = new System.Windows.Forms.Label();
this.progressBar = new DaveyM69.Windows.Forms.ProgressBar();
this.button = new System.Windows.Forms.Button();
this.SuspendLayout();
this.label.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label.AutoEllipsis = true;
this.label.Location = new System.Drawing.Point(12, 9);
this.label.Name = "label";
this.label.Size = new System.Drawing.Size(200, 13);
this.label.TabIndex = 0;
this.label.Text = "Working...";
this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.progressBar.Location = new System.Drawing.Point(12, 25);
this.progressBar.Marquee = false;
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(200, 23);
this.progressBar.TabIndex = 1;
this.progressBar.Text = "0%";
this.progressBar.Value = 0;
this.button.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.button.Location = new System.Drawing.Point(137, 54);
this.button.Name = "button";
this.button.Size = new System.Drawing.Size(75, 23);
this.button.TabIndex = 2;
this.button.Text = "&Cancel";
this.button.UseVisualStyleBackColor = true;
this.AcceptButton = this.button;
this.ClientSize = new System.Drawing.Size(224, 89);
this.ControlBox = false;
this.Controls.Add(this.button);
this.Controls.Add(this.progressBar);
this.Controls.Add(this.label);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ProgressForm";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Progress";
this.ResumeLayout(false);
}
protected virtual void OnDoWork(DoWorkEventArgs e)
{
DoWorkEventHandler eh = DoWork;
if (eh != null)
eh(this, e);
}
protected virtual void OnProgressChanged(ProgressChangedEventArgs e)
{
ProgressChangedEventHandler eh = ProgressChanged;
if (eh != null)
eh(this, e);
}
protected virtual void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
{
RunWorkerCompletedEventHandler eh = RunWorkerCompleted;
if (eh != null)
eh(this, e);
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
RunWorkerAsync();
}
private void Progress(object state)
{
DaveyM69.ComponentModel.ProgressChangedEventArgs e =
(DaveyM69.ComponentModel.ProgressChangedEventArgs)state;
if (e.TaskName != NoMessageChange)
Text = e.TaskName;
if (e.OperationName != NoMessageChange)
label.Text = e.OperationName;
if (workerReportsProgress && e.ProgressPercentage != NoProgressChange)
{
progressBar.Value = e.ProgressPercentage;
OnProgressChanged(e);
}
}
public void ReportProgress(int progressPercentage)
{
ReportProgress(
NoMessageChange, NoMessageChange, progressPercentage, null);
}
public void ReportProgress(string taskName, string operationName)
{
ReportProgress(taskName, operationName, NoProgressChange, null);
}
public void ReportProgress(string taskName, string operationName,
int progressPercentage, object userState)
{
DaveyM69.ComponentModel.ProgressChangedEventArgs state =
new ComponentModel.ProgressChangedEventArgs(
taskName, operationName, progressPercentage, userState);
if (asyncOperation == null)
progress(state);
else
asyncOperation.Post(progress, state);
}
private void RunWorkerAsync()
{
if (!isBusy)
{
isBusy = true;
button.Enabled = workerSupportsCancellation;
asyncOperation = AsyncOperationManager.CreateOperation(null);
work.BeginInvoke(argument, null, null);
}
}
private void SetWorkerReportsProgress()
{
if (InvokeRequired)
new MethodInvoker(SetWorkerReportsProgress).Invoke();
else
{
progressBar.Marquee = !workerReportsProgress;
}
}
private void SetWorkerSupportsCancellation()
{
if (InvokeRequired)
new MethodInvoker(SetWorkerSupportsCancellation).Invoke();
else
{
if (isBusy && !cancellationPending)
button.Enabled = workerSupportsCancellation;
else
button.Enabled = false;
}
}
private void Work(object obj)
{
bool cancelled = false;
Exception error = null;
object result = null;
DoWorkEventArgs doWorkEventArgs = new DoWorkEventArgs(obj);
try
{
OnDoWork(doWorkEventArgs);
if (doWorkEventArgs.Cancel)
cancelled = true;
else
result = doWorkEventArgs.Result;
}
catch (Exception ex)
{
error = ex;
}
RunWorkerCompletedEventArgs state = new RunWorkerCompletedEventArgs(
result, error, cancelled);
asyncOperation.PostOperationCompleted(completed, state);
}
}
}
namespace DaveyM69.ComponentModel
{
public class ProgressChangedEventArgs : System.ComponentModel.ProgressChangedEventArgs
{
private string operationName;
private string taskName;
public ProgressChangedEventArgs(
string taskName, string operationName,
int progressPercentage, object userState)
: base(progressPercentage, userState)
{
this.taskName = taskName;
this.operationName = operationName;
}
public string OperationName
{
get { return operationName; }
}
public string TaskName
{
get { return taskName; }
}
}
}
|
|
|
|
|
if only someone would write an article on this interesting subject...
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'm going to be concentrating on WP7 dev for the forseeable future so WPF will also be a logical move for desktop I suppose. I have built up quite a library of useful components/controls etc for WinForms over the years that I'm combining into one demo project to share.
|
|
|
|
|
I agree
Thanks for the post from musefan, it did help me quite a lot. My code seemed to work fine, then I renamed a couple of things and then it didn't update the progressbar correctly anymore, then I undid the changes and it still doesn't work I know it did work though so I must just be missing something
|
|
|
|
|
Here is some code in one of my methods:
webBrowser1.Focus();<br />
System.Windows.Forms.SendKeys.Send("{PGDN}");
I'm using this to force the webbrowser to scroll down so that a picture on the site I'm using is on screen.
Then I use:
findClick();
I have coded this to mean: using(image1) find image on screen and click.
It works fine.
MY PROBLEM IS:
(here is the next line of code):
webBrowser1.Focus();<br />
System.Windows.Forms.SendKeys.Send("{PGDN}");<br />
Point one = this.Location;
How do I wait for a certain amount of time before executing the next line of command?
THREAD.SLEEP DOESN'T WORK!!!!!!!!!!
This command freezes the form and doesn't do anything for this problem. I also cannot use timers because I need the code to remain in this method (preferably in one line, like thread.Sleep)
How would I go about doing this?
ANOTHER SIMILAR PROBLEM:
using:
webBrowser1.Navigate("http://google.com");<br />
second command;<br />
third command;
This doesn't wait for the first command to finish so I would like to place a timer that says wait(5000) then continue.
I KNOW ABOUT DOCUMENTCOMPLETED events, I'm using this as an example!
|
|
|
|
|
your problem description is incomplete and hard to read and understand, however I can tell you this:
1. a WinForm app needs a responsive GUI, so GUI event handlers should not contain blocking calls nor long winding calculations.
2. Thread.Sleep() is a blocking call; it should never be called by the main thread.
3. problems that are inherently asynchronous can't be solved synchronously, i.e. the correct solution has to include extra threads and/or events.
4. if and when someone tells you Application.DoEvents() will solve it for you, do not go that route, it is a recipe for failure later on.
And before you ask to "clarify" or "show code", I suggest you make things a lot clearer, showing code in PRE tags, and explaining where the code resides, and on what thread it runs, and when, etc. Showing fractions of some method, without much context, isn't very informative.
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.
|
|
|
|
|
Luc is quite right, Thread.Sleep won't help.
Instead, set up a class level Timer, with a (say) 1/10th second interval. Use a counter in the Timer.Tick event to allow your five seconds to elapse, and then continue your processing.
The other solution is as Luc says to move your processing code onto a separate thread, which you can Sleep without affecting the GUI. Remember that you can only access UI components from the GUI thread though!
Real men don't use instructions. They are only the manufacturers opinion on how to put the thing together.
Digital man: "You are, in short, an idiot with the IQ of an ant and the intellectual capacity of a hose pipe."
|
|
|
|
|
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.
|
|
|
|
|
Your first issue...
Use SendWait instead of Send...
System.Windows.Forms.SendKeys.SendWait("{PGDN}");
...consider putting this on a separate thread - as Luc has said you do not want to be making the UI wait for anything that does not complete almost instantly
Your navigate problem (second issue)...
add an event handler for the DocumentCompleted event of the WebBrowser control, then add second and third command in there...
WebBrowser wb = new WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
Don't vote my posts down just because you don't understand them - if you lack the superior intelligence that I possess then simply walk away
|
|
|
|
|
Hi
I'm using C# version 2008 on Win 7.
I am building an app and need to add a console page.
In delphi I would simply click new item and click on console.
With C# there is no reference to a console item to add.
Am I missing something or is this a limitation of the Express addition?
If so, is there a workaround?
Bob
|
|
|
|
|
No, there is no such thing as a "Console Page", not even in the Ultimate editions of Visual Studio.
If you want a console window, you'll have to create one yourself with, at the very least, AllocConsole, AttachConsole, FreeConsole Win32 functions.
|
|
|
|
|
Do you mean adding a console window to a non-console app? If so - this tip[^] may help.
|
|
|
|
|
It's Easy ,
Click Menu Project -> Project Properties -> Select Application Tab -> In Out Put Type ComboBox Select "Console Application"
Have a good day !
I know nothing , I know nothing ...
|
|
|
|
|
Hy experts
I need a little help here. Can anybody tell me how to select
a radio button from another program knowing the name,id or text of the radio button.
I want to automate internet explorer by checking the "First Name" radio button then pressing the "Send" button.
This is the code I'm using to set the focus to internet explorer:
using System;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class getWindow
{
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string IpClassName, string IpWindowName);
[DllImport("user32.dll")]
public static extern int SetForegroundWindow(IntPtr hWnd);
public static void Main(string[] args)
{
IntPtr iHandle = FindWindow(null, "Details - Windows Internet Explorer");
SetForegroundWindow(iHandle);
}
}
Any help would be appreciated.
Thank you in advance.
|
|
|
|
|
For some reason this will not work on my machine (Vista Enterprise sp2)
My messagebox display says "697538 seconds 697538 (this increments each time I run it but is always the same as the first number) seconds At second 0" .
When I run the second block of code it says "Last input ticks is 8 and idle ticks is 697791247 (this increments each time I run it) .
I got code example from this site, any idea as to why this won't work for me or what I am doing wrong? Thank you for reading.
http://www.geekpedia.com/tutorial210_Retrieving-the-Operating-System-Idle-Time-Uptime-and-Last-Input-Time.html[^]
public static void timerThread()
{
int timerCount = 0;
while (true)
{
MessageBox.Show("Start counting");
Thread.Sleep(10000);
int systemUptime = Environment.TickCount;
int LastInputTicks = 0;
int IdleTicks = 0;
LASTINPUTINFO LastInputInfo = new LASTINPUTINFO();
LastInputInfo.cbSize = (uint)Marshal.SizeOf(LastInputInfo);
LastInputInfo.dwTime = 0;
LastInputTicks = (int)LastInputInfo.dwTime;
IdleTicks = systemUptime - LastInputTicks;
string one = Convert.ToString(systemUptime / 1000) + " seconds";
string two = Convert.ToString(IdleTicks / 1000) + " seconds";
string three = "At second " + Convert.ToString(LastInputTicks / 1000);
MessageBox.Show(one + " " + two + " " + three);
Thread.Sleep(60000);
}
}
public static void timerThread()
{
int timerCount = 0;
int LastInputTicks = 0;
int IdleTicks = 0;
while (true)
{
MessageBox.Show("Start counting");
Thread.Sleep(10000);
int systemUptime = Environment.TickCount;
LASTINPUTINFO lastInPut = new LASTINPUTINFO();
lastInPut.dwTime = 0;
lastInPut.cbSize = (uint)Marshal.SizeOf(lastInPut);
lastInPut.dwTime = (uint)Marshal.SizeOf(lastInPut);
LastInputTicks = (int)lastInPut.dwTime;
IdleTicks = systemUptime - LastInputTicks;
MessageBox.Show("Last input ticks is " + LastInputTicks.ToString() + " and idle ticks is " + IdleTicks.ToString());
Thread.Sleep(60000);
}
}
|
|
|
|
|
Hi
Not sure about this, but where are you calling the GetLastInputInfo method to fill the lastInPut struct?
I are Troll
|
|
|
|
|
This simple test code works for me:
using System;
using System.Runtime.InteropServices;
using System.Timers;
namespace LastInputTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press Enter to exit!");
using (Timer timer = new Timer(1000))
{
timer.AutoReset = true;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
while (Console.ReadKey().Key != ConsoleKey.Enter)
{
Console.WriteLine();
}
}
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
LASTINPUTINFO lii = new LASTINPUTINFO();
lii.cbSize = LASTINPUTINFO.Size;
NativeMethods.GetLastInputInfo(ref lii);
Console.WriteLine(lii.dwTime);
}
}
internal static class NativeMethods
{
[DllImport("User32.dll", SetLastError = true)]
public static extern int GetLastInputInfo(ref LASTINPUTINFO lii);
}
[StructLayout(LayoutKind.Sequential)]
internal struct LASTINPUTINFO
{
public static readonly int Size = Marshal.SizeOf(typeof(LASTINPUTINFO));
public int cbSize;
public uint dwTime;
}
}
|
|
|
|
|
Thank you, I was able to get this to work
|
|
|
|
|
You're welcome
|
|
|
|
|
i have got some unicode values , i need to get the relevant string(letters) from that, i tried with .net encoding , but didn't find a way .
any idea how to get it.
thanx in advance.
|
|
|
|
|
There is nothing to encode, a Unicode value is already a letter so it can be displayed directly.
I must get a clever new signature for 2011.
|
|
|
|
|
prasadbuddhika wrote: i have got some unicode values
You mean an array with bytes that represent characters? Something like this[^];
String myText = System.Text.Encoding.Unicode.GetString(myBuffer);
I are Troll
|
|
|
|
|
Hi all,
I am currently employed by a company in Tampa, FL as a .NET Engineer with a primary role in WPF development.
We are currently searching for solid WPF candidates to bring on board. This company has been in the area for
30+ years, is a privately held family owned corporation, and has very low turnover. Pay and benefits are very competitive and work environment is great.
One prerequisite however is that you would need to live in Florida in or near Tampa i.e. no telecommuting.
If you're interested send me a message via Code Project.
Thanks,
Azad
|
|
|
|
|
Azad. You should ask this in the jobs board. The language specific forums is not the appropriate place for a question like this.
|
|
|
|
|
Hi Pete,
Could you point me to the jobs board - I looked but wasn't able to find a forum specific for jobs?
Thanks in advance,
Azad
|
|
|
|
|