Controls look different at runtime and design time - c#

I have a regular button (or any other control), which at design time looks 3D like this:
And at runtime looks flat like this:
Of course I want it to look 3D, but I can't see any reason, option or property to make it 3D. I thought that maybe it's a .NET issue, but even targeting .NET 4.5.3 didn't help.
P.S: Obviously I have windows 7, so this can't be the issue

Normally, the Application.EnableVisualStyles() method is called by default in the static void Main() method, inside the program.cs file. Maybe you're maintaining an older app, or someone removed that line at some point. Check to see if it's missing.
static class Program
{
[STAThread]
static void Main()
{
// Enable visual styles for your application.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
Technically, you can call that method from anywhere in your application, but then controls that have already been drawn may retain the older "flat" look. Best to leave it in the program.cs file, and execute it before you start up the message loop for your application.

Add this code into Form_load() :
private void Form1_Load(object sender, EventArgs e)
{
button1.FlatStyle = FlatStyle.Standard;
}

Application.EnableVisualStyles();
is what you need to add to program.cs

Related

Visual studio does not show UI while running app

I have been working on c# for about 3 hours and Visual Studio does not show the UI while running the application. It shows the UI in designer but after compiling and running, it just goes blank.
Two things to test:
In the code file Program.cs, you will find something like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Does the name of the form in the line Application.Run match the name of your form?
Your form's code behind (Form1.cs) should have a constructor looking like this
public Form1() // Where the name of the constructor must match the one of the form class.
{
InitializeComponent();
// Your code goes here (if any) ...
}
Does it have this constructor? If yes, does it call InitializeComponent?
InitializeComponent is very important, because it creates the controls and configures the form. You may have replaced it with your own code. Always call it before your initialization code.
I guess the entry point if your application is wrong. Check the solution properties (right click on your application/solution in the solution explorer -> properties ) for the correct entry point.
It looks like you have more than one form.
Go to the Program.cs file and verify if the class of the form is in Application.Run() method
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main ()
{
Application.EnableVisualStyles ();
Application.SetCompatibleTextRenderingDefault (false);
Application.Run (new urltetx());
}
}

How to make a picturebox in a form visible by referencing a method from another class

my image "Input1GreenLight" needs to be visible when my FormCall thread method is called. However, in my "while (true)" infinite loop, I call the class Form1.setLights(), which calls the method in the Form1.cs, but I can not access Input1GreenLight as it says "this member can not be reference from a static context".
So I realize the issue, but I'm not sure how to fix/address it, suggestions appreciated and please find code snippets below (please keep in mind, FormCall is being called through a new thread, and thus is not blocking my program). Also, do not mind GlobalVars.Input1, that is being used by a separate piece of code.
Code from my C# Script
public static void FormCall()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
while (true)
{
Form1.setLights();
}
}
Code from my Form1 Script
public static void setLights()
{
Input1GreenLight.Visible = GlobalVars.Input1;
}
Input1GreenLight is the picturebox's name, just to clarify again. I am new to C#, familiar with C/C++. Thank you in advance

.Net Program with both WinForm and Console Interfaces

I have a simple question and I'm sure it's been answered, but I can't seem to find the solution I'm looking for.
My basic question is that I've created a console app in .Net that runs automatically on a task scheduler every day, but now my clients also want a windows form-based interface that they can use to run special runs (they use the GUI to specify a few parameters - such as specific dates, etc - to make the program run a bit differently).
The way I thought to do this would be to convert my console app to a WinForm solution and to include Command Line Arguments for when I wanted it to run as the original console app with defaults, but I'm thinking that's not the right way since it would still involve a form load.
My other thought was to convert the "engine" part to a DLL and to make 2 executables - One a console app and one a winforms app, but I'm not sure if that's right either / could lead to more maintenance.
What is the correct way to do this?
I'm writing this in VB, but am equally comfortable with C# solutions if that is easier for you.
Thanks!!
Typically, I'd split the logic into a library, then make a simple console app and a simple Forms app to call into the logic in the library.
You can then distribute these separately and use them as they are intended, without duplication of code.
You can modify your Program.cs to accept arguments, then if some args had been passed to your app prcess them and exit from main, else start your main form, something like this:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
if (ProcessCommandLine(args))
return;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static bool ProcessCommandLine(string[] args)
{
//Process it, if some has been processed return true, else return false
}
}
Or you can make the form invisible and go with your first option, reading the commandline.
here is a way of making the invitial form invisible. Form Invisible
Three projects as Reed suggested is a correct approach, however if you really need 1 executable (which we for some reason really wanted in one case) you can do following:
static class Program
{
[STAThread]
static void Main(string[] args)
{
if (args[0]== "-ui")
{
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.Run(new MyFormWork());
}
else if (args[0] == "-console")
{
Helper.AllocConsole();
DoYourConsoleWork();
Helper.FreeConsole();
}
}
public static class Helper
{
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
[DllImport("kernel32.dll")]
public static extern Boolean FreeConsole();
}
1: you can use XML for arguments. your console just need to read XML for its argument.
then create a form app just for editing XML and save.
Benefit:
your app is running by task scheduler so your form do not need to .
for user it's easy to open form app and change something that will save to xml
Console --run every day without any notice
Argument.xml -- argument for Console .
Form -- user interface
2: you can mix both within a form but it will run every day in form base not good idea

Form closing itself

I'm new to C# (switching from Java) and i'm having a bit of trouble understanding GUI in C#
Ill just paste the Code i have and let that explain the most part.
Main Class:
Frame frame;
keepRunning = true;
public GraphicsComponent()
{
frame = new Frame();
frame.Show();
}
public void run()
{
while (keepRunning)
{
Console.WriteLine("Running");
}
}
public static void Main()
{
GraphicsComponent gameComponent = new GraphicsComponent();
gameComponent.run();
}
using the frame.Show() method, it appears and disappears for a quick moment. but the "running" loop is run.
The other way i have seen is another method called ShowDialoge(), that one keeps the window open but blocks the rest of the code from running until it is closed.
The way i want to use it is basically how GUIs work in Java. Where i can reference an object (and it's components) as needed in the rest of my code.
Thanks heaps!
Edit: There is alot of confusion, so here is my Frame class:
public partial class Frame : Form
{
public Frame()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
A normal way to kick off a winforms application is by file->new winforms project. WHen you do this you get "Program.cs", which contains your Main method - the entry point into your application. From there you have code like this:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new ConfigForm());
}
In this example I kick off a new "ConfigForm"" that is a Form, and contains in it's ctor some code that looks like this:
public ConfigForm()
{
InitializeComponent();
// Other init work here
}
I create the form by right-clicking in the project and adding a new form.
You might want to look into the Application.Run method, see here. You can specify a "Main Form" which is going to be the main form that runs for the duration of the application, and when closed ends the application, or you can specify other options if you want. Perhaps the simplest solution is to start a main form, and since the form is live for the duration of the application, you can kick off other long-running code inside that form. If it's code that you want to be executing all the time performing some sort of background operation then you might want to fire it off in it's own thread. However, threading is hard so if you're new to c# / .net I'd try to stay away from threading unless you need it.

Windows Forms GUI hangs when calling OpenFileDialog.ShowDialog()

my project a three tier architecture project talking to a WCF service in the backend. When the backend is able to fetch data from the service, it notifies the business layer using publish-subscribe, which in return notifies the GUI layer.
I have added an OpenFileDialog to my UI design using Visual Studios designer. A button event handler calls the ShowDialog message. However, once I click the button, the whole UI hangs.
Having googled around a bit, I found out that using delegates is the preferred way to handle tasks like this. However, with nor without delegate the problem persists.
Currently my code looks like this:
private void bOpen_Click(object sender, EventArgs e)
{
Func<Image> del = delegate
{
OpenFileDialog d = new OpenFileDialog();
if (d.ShowDialog() == DialogResult.OK)
{
return Image.FromFile(d.FileName);
}
return null;
};
Invoke(del);
}
I'm coming from the Java world, so I'm not really familiar with the intricacies of C# UI programming.
Anything I'm missing here?
openFileDialog1->ShowHelp = true;
I put this line in my code then the problem was solved.
I seem to have solved the problem adding the [STAThread] Attribute to the main method. I was told to do so once I ran the program in a debugger - which I hadn't done before because I ran the service from Visual Studio and the client regularly from Windows.
[STAThread]
public static void Main(string[] args)
{
GUI gui = new GUI();
gui.ShowDialog();
}
Can anybody explain what exactly is going on though
This tends to be an environmental problem, when you use OpenFileDialog a lot of shell extensions get loaded into your process. A misbehaving one can easily screw up your program. There are a lot of bad ones out there.
Debugging this is difficult, you need an unmanaged debugger since these shell extensions are unmanaged code. You might be able to tell something from the call stack when you break in after the deadlock. Windows debugging symbols required, enable the Microsoft symbol server. But the most effective approach is to use SysInternals' AutoRuns utility. Start by disabling all of the shell extensions that were not produced by Microsoft. Then start re-enabling the ones you cannot live without one by one.
And, as you found out, these shell extension expect to run on an STA thread and fail miserably when they don't get it. The UI thread of a program must always be STA, also to support the clipboard and drag-and-drop and various kinds of controls like WebBrowser. Normally always taken care of automatically by the [STAThread] attribute on the Main() method, put there by the project template. And the Application.Run() call, required to implement the STA contract. Deadlock when you don't.
I believe the "delegate" prefered way actually refers to using a separate thread.
I'm gonna give you an example using BackgroundWorker.
It would look like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
m_Worker.DoWork += new DoWorkEventHandler(m_Worker_DoWork);
m_Worker.ProgressChanged += new ProgressChangedEventHandler(m_Worker_ProgressChanged);
m_Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(m_Worker_RunWorkerCompleted);
}
void m_Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Usually, used to update a progress bar
}
void m_Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Usually, used to add some code to notify the user that the job is done.
}
void m_Worker_DoWork(object sender, DoWorkEventArgs e)
{
//e.Argument.ToString() contains the path to the file
//Do what you want with the file returned.
}
private void bOpen_Click(object sender, EventArgs e)
{
OpenFileDialog d = new OpenFileDialog();
if (d.ShowDialog() == DialogResult.OK)
{
m_Worker.RunWorkerAsync(d.FileName);
}
}
BackgroundWorker m_Worker = new BackgroundWorker();
}
Now, as for the reason your UI "hangs", it's because by default, your operation runs on the UI thread, so if you run something heavy the UI won't respond.
I also met this problem. And I tried all the solution here and none can solve it. Then I change the target framework from .Net Framework 4.7 to 4.6.2, the problem solved...
I think my problem is different, as none of the above solutions worked for me.
I wrote temporary code to set the OpenFileDialog.FileName property to something not null or empty string (it was empty string when the hang up occured), and I restarted my computer. When I started up Visual Studio again, and ran it, it worked again without hanging up.

Categories

Resources