This question already has answers here:
How do I convert a .NET console application to a Winforms or WPF application
(2 answers)
Closed 8 years ago.
I want to do some changes here, I want to convert this application to winforms. And i want to store these output into a text file, How can I do it? please help
using System;
using System.Threading;
public static class Program
{
public static void Main()
{
// Create a Timer object that knows to call our TimerCallback
// method once every 2000 milliseconds.
Timer t = new Timer(TimerCallback, null, 0, 1000);
// Wait for the user to hit <Enter>
Console.ReadLine();
}
private static void TimerCallback(Object o)
{
// Display the date/time when this method got called.
Console.WriteLine(DateTime.Now);
// Force a garbage collection to occur for this demo.
GC.Collect();
}
}
Output of this application.
Source Stackoverflow
Go to application > and change is Application type to Winform and then point start up object at Sub Main
Right click on the solution and select "Add Reference"
Select System.Windows.Forms and hit OK
Related
This question already has answers here:
Open two console windows from C#
(4 answers)
Closed 3 years ago.
We want to troll our teacher, we want to start a new console window when he inputs something (arbitrary value) invalid.
Is there a way that we could start a new console window from Main?
using System;
using System.Diagnostics;
static void Main(string args)
{
Process.Start();
}
Sure ;)
System.Diagnostics.Process.Start("CMD.exe");
This question already has answers here:
How to stop C# console applications from closing automatically? [duplicate]
(9 answers)
Closed 3 years ago.
Im running .NET Core 2.2 and just want to create a simple Console Application that reads one value and prints it out. Yes i know there is millions of examples of this but my problem is that none of them works for some reason. When i press Enter the application stops.
Here is the simple code that just writes the first line but then do nothing:
static void Main(string[] args)
{
Console.WriteLine("I want to write a value here");
var theValue = Console.ReadLine();
Console.WriteLine(theValue);
}
Is there any configuration i have to do in Visual Studio 2017 to make the Console read my value i write? Or anything else that makes the Console close and program to end when i press enter?
The application doesn't stop, It simply ends since it prints out the result of your line and moves to next line since there is no more code to run it simply closes the application
Add Console.ReadLine(); on the end so that it doesn't close after first enter
static void Main(string[] args)
{
Console.WriteLine("I want to write a value here");
var theValue = Console.ReadLine();
Console.WriteLine(theValue);
Console.ReadLine();
}
you need to make the app wait and not exit using an additional Console.Read. Try like:
var theValue = Console.ReadLine();
Console.WriteLine(theValue);
Console.Read();
This question already has answers here:
What is the correct way to create a single-instance WPF application?
(39 answers)
Closed 7 years ago.
I've Created a Music Player using Visual Studio 2012 Windows Form C#. now I want the user to be able to play songs in windows explorer such as other players(Windows Media Player,Winamp,etc.) with my player.
I already found the way to File association!
but I need to prevent my application from running multiple instance(as WMP&... don't) and I want to get the songs Paths too to send them to my application(already started).
For example User Select 3 Songs in a directory in windows explorer & Press Enter so my application / and execute my AddFiles Function (add the supported files to playlist and ...)
I tried mutex it solves the first part(just single instance) but can't get arguments from it!
I also tried this but No chance :( it gave error!
** I already triedWhat is the correct way to create a single instance application? "Matt Davis" Answer and it makes my application to be single instance only and bring to front part was awesome but didn't send arguments to my running process so It couldn't solve my problem!
any Help would be in advance :)
UPDATE:
I don't understand while I haven't get my problem solved why experts close the question!? :| :/
UPDATE 2 (FOUND THE SOLUTION):
ok Finally I've got the solution :)
this link helped me to get paths of selected files in explorer by clicking on a context-menu item:
.NET Shell Extensions - Shell Context Menus
real easy :)
Hope this help others too!
I use this: https://code.msdn.microsoft.com/windowsapps/CSWinFormSingleInstanceApp-d1791628
It's single instance, and supports command line args. My program is started like this:
[STAThread]
static void Main(String [] args) {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 mf = new Form1(); // your form
SingleInstanceAppStarter.Start(mf, StartNewInstance);
}
...
private static void StartNewInstance(object sender, StartupNextInstanceEventArgs e) {
String cmdArg = e.CommandLine[1]; // yes, 1 to get the first. not zero.
...
}
You'll also need this:
class SingleInstanceAppStarter
{
static SingleInstanceApp app = null;
public static void Start(Form f, StartupNextInstanceEventHandler handler)
{
if (app == null && f != null)
{
app = new SingleInstanceApp(f);
}
app.StartupNextInstance += handler;
app.Run(Environment.GetCommandLineArgs());
}
}
and this:
class SingleInstanceApp : WindowsFormsApplicationBase
{
public SingleInstanceApp() { }
public SingleInstanceApp(Form f)
{
base.IsSingleInstance = true;
this.MainForm = f;
}
}
Note that both of those classes use the Microsoft.VisualBasic.ApplicationServices assembly (You'll have to reference it).
I use AllocConsole() to open a Console in a winform application.
How can I prevent the application from exiting when the Console is closed?
EDIT
The update of completionpercentage from time to time is what I want to show in console
void bkpDBFull_PercentComplete(object sender, PercentCompleteEventArgs e)
{
AllocConsole();
Console.Clear();
Console.WriteLine("Percent completed: {0}%.", e.Percent);
}
I tried the richtextBox as the alternative
s =(e.Percent.ToString());
richTextBox1.Clear();
richTextBox1.AppendText("Percent completed: " +s +"%");
But I can't see the completionpercentage update time to time. It only appears when it is 100% complete.
Any alternative?
I know this is a task that seldom pops up but I had something similar and decided to go with a couple hacks.
http://social.msdn.microsoft.com/Forums/vstudio/en-US/545f1768-8038-4f7a-9177-060913d6872f/disable-close-button-in-console-application-in-c
-Disable the "Close" button on a custom console application.
You're textbox solution should work as well. It sounds a lot like your calling a function from the main thread that is tying up the form which is also on the main thread and is causing you grief when updating your textbox. Consider creating a new thread and either an event handler to update your textbox or use the invoke methodinvoker from the new thread to update the textbox. Link below from an already answered question on how to complete this.
How to update textboxes in main thread from another thread?
public class MainForm : Form {
public MainForm() {
Test t = new Test();
Thread testThread = new Thread((ThreadStart)delegate { t.HelloWorld(this); });
testThread.IsBackground = true;
testThread.Start();
}
public void UpdateTextBox(string text) {
Invoke((MethodInvoker)delegate {
textBox1.AppendText(text + "\r\n");
});
}
}
public class Test {
public void HelloWorld(MainForm form) {
form.UpdateTextBox("Hello World");
}
}
Refer to the answers over here. As mentioned in the answers, there is no way to stop the application from getting closed.
But as a workaround, you can have your own text output solution described in one of the answers.
You can build first the console application that recieves arguments and writes it to the console. Place it, where the main application starts.
From main application you can first kill process and then reopen it with a new argument.
It's the altarnative way.
This question already has answers here:
Run one instance of program
(2 answers)
Closed 9 years ago.
There is an option in my application to hide the window - form.hide(), and to put an notifyicon in the system tray, and when you click the notifyicon there will be a form.show().
If someone will try to run two instances of the app, I want
a. not to run the new instance
b. to show the window of the first instance
I already have a loop to check if a process with the same name exists.
and I can tell the new app not to run ( return in the program.cs before Application.run(new form()))
but I yet have to tell the first app to show its main window.
I have the process (of the first instance) , i can get its handle its id etc.
the question
How to show the window using it's process?
For the first part of the question, here is what you can do. Add this in the Main before you show your form. The benefit of this is that you don't check by process name (which might not be unique), but you create a mutex which is somehow "global".
using (Mutex applicationMutex = new Mutex(true, "SomeRandomTextHere", out mutexCreated))
{
if (!mutexCreated)
{
// Application is already running. Aborting..
return;
}
// Application.Run(..) goes here, plus other interesting stuff
}
For the second part of your question I would suggest the following:
Create a named event and set it initially to false. Then create a worker thread in your application that monitors this event. When it is signaled, Invoke your Show method from your main form.
Another approach is to search for the window handle of the main process and bring it to front. This article can give you ideas.
Bear in mind that doing a loop through all processes is not as efficient as using a mutex. If you don't care about speed, clean code and you just want this app to work then use this loop.. To me code is poetry.
Rewrote the code just for you this will give you exactly what you want. It will check for duplicates and focus the screen when a duplicate is opened.
EventWaitHandle ProgramOpen = new EventWaitHandle(false, EventResetMode.ManualReset, "ProgramOpen198472");
EventWaitHandle FocusProgram = new EventWaitHandle(false, EventResetMode.ManualReset, "FocusMyProgram198472");
private delegate void focusConfirmed(); Thread FocusCheck;
private void focus() { FocusProgram.WaitOne(); this.Invoke(new focusConfirmed(()=>{this.Show(); this.BringToFront();}));}
private void Form1_Load(object sender, EventArgs e)
{
if (ProgramOpen.WaitOne(0))
{
FocusProgram.Set();
this.Close();
}
ProgramOpen.Set();
}
private void HideButton_Click(object sender, EventArgs e)
{
this.Hide();
FocusProgram.Reset();
FocusCheck = new Thread(focus);
FocusCheck.Start();
}
private void showToolStripMenuItem_Click(object sender, EventArgs e)
{
FocusProgram.Set();
}