I want to print the name of the selected file on label1 when the FileDialog closes successfully using the openFileDialog_FileOk in C#, but the openFileDialog_FileOK is never called.
Sorry for bad English.
namespace Graph_Win_Forms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
label1.Text = "Dosya: " + openFileDialog1.FileName;
}
}
}
I tried delete code and WinForms Element but it didn't work
I suspect that you have copied that code from an online sample somewhere and you have ignored the fact that, if you expect that method to be invoked when an event is raised, you need to register it as an event handler. The most immediate option would be this:
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.FileOk += openFileDialog1_FileOk;
openFileDialog1.ShowDialog();
What was likely done in the first place was that an OpenFileDialog was added to the form in the designer and then the event handler generated in the designer. You could do that too, instead of creating the OpenFileDialog in code. If you do that, you can select an existing method in the designer rather than creating a new one.
Having said that, I would normally not handle that event anyway. If you're displaying one or more dialogues in different places and you want to write the code to execute on OK in one place then it makes sense to handle that event. It would also make sense if the event handler was in a different code file to the code that shows the dialogue. If you are only display the dialogue in one place though, I'd probably just check the result of ShowDialog and act on OK.
simple way to use below code.
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
if (openfiledialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = "Dosya: " + openfiledialog1.FileName;
}
}
if you are using the toolbox you have to declare your event 'openFileDialog1_FileOK' in property->Event->FileOk and remove the initialization of the OpenFileDialog instance because the design mode does it automatically.
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
label1.Text = "Dosya: " + openFileDialog1.FileName;
}
Related
I want to know if there is any event when you click on the rest of the screen and not the Windows Form the Form closes. Is it because of the ShowDialog()?
My Main Form is just with a notifyIcon and when I click it I call Form1.ShowDialog();
Main.cs:
private void ShowForm1(object sender, EventArgs e)
{
form1.Left = Cursor.Position.X;
form1.Top = Screen.PrimaryScreen.WorkingArea.Bottom - form1.Height;
form1.ShowDialog();
}
Form1.cs:
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "Test";
}
You need to run the dialog box non-modally, not modally. Think about it, when you run it modally, the dialog box takes over the UI and plays games with mouse-clicks elsewhere, preventing you from running. You don't want it to be modal anyway.
I created a simple Windows form with a button that includes this handler to open a small AutoCloseDialog form I created (and populated with a few controls):
private void button1_Click(object sender, EventArgs e)
{
var dlg = new AutoCloseDialog();
dlg.Show(this); //NOTE: Show(), not ShowDialog()
}
Then, in the AutoCloseDialog form, I wired up the Deactivate event. I did it in the designer (where this code is generated):
this.Deactivate += new System.EventHandler(this.AutoCloseDialog_Deactivate);
Finally, here is the handler for the Deactivate event.
private void AutoCloseDialog_Deactivate(object sender, EventArgs e)
{
this.Close();
}
I think this does what you are asking.
Yes, you can create a similar function like this, which closes the Form if the Form lost focus (in Form1.cs)
public void Form_LostFocus(object sender, EventArgs e)
{
Close();
}
and then you add the LoseFocus EventHandler (in Form1.Designer.cs):
this.LostFocus += new EventHandler(Form_LostFocus);
I want to make a windows form using C# to check if a file exist.
I've tried this one:
private void test_Click(object sender, EventArgs e)
{
var app1 = (#"C:\Users\frangon\Desktop\Spectrum-Check.EXE");
test.Text = File.Exists(app1).ToString();
}
If possible, I don't want to click it. I just want it to show as "True" if the file exist, or "False" if the file doesn't exist.
You can add an event to trigger when the form loads:
And then in your code behind:
private void Form1_Load(object sender, EventArgs e)
{
string app1 = #"C:\Users\frangon\Desktop\Spectrum-Check.EXE";
test.Text = File.Exists(app1).ToString();
}
I'm newbie of winform. I have opened form2 form a linklabel in form1 using :
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
FrmAddMov frmAddMov = new FrmAddMov();
if(frmAddMov.ShowDialog() == DialogResult.OK)
{
this.Invalidate();
//or
this.Refresh();
}
}
I thought form1 will reload after I submit form2, but not. Please tell me the right way to do it. Thanks a lot, and sorry if my english is too bad.
Gentleman's answer will work, but it can be improved.
When showing a form using ShowDialogthan it is best practice to dispose of that form, and the easiest way to do that is by the using statement
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
using (FrmAddMov frmAddMov = new FrmAddMov())
{
if (frmAddMov.ShowDialog() == DialogResult.OK)
{
FormLoad();
}
}
}
This way you are always 100% sure that all resources for frmAddMov will be cleaned up.
Move everything in your form load event to a method say FormLoad. You may want to add few other statements which you are expecting form reload will do for you. Call this method when your 2nd form closes.
Something like this
private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
FrmAddMov frmAddMov = new FrmAddMov();
if(frmAddMov.ShowDialog() == DialogResult.OK)
{
FormLoad();
}
}
I have made a little program that can start application (like quick launch in your taskbar)
You can add applications and it shows the icon of the .exe and the name of the file, and when you click on it (button) it starts the application.
When you close the program and start it again everything is empty, so i want to save it somewhere.
I see people on the internet do it with:
private void QuickStarter_FormClosed(object sender, FormClosedEventArgs e)
{
Properties.Settings.Default.Button1 = button1.Text;
Properties.Settings.Default.Save();
}
private void QuickStarter_Load(object sender, FormClosedEventArgs e)
{
button1.Text = Properties.Settings.Default.Button1;
}
This doesn't work, but they use it for text fields and input boxes i don't know if it is even possible for a button.
Question:
Can someone tell me what the best way is, for saving button input and load it back in when the application starts again? Or maybe i have to do it with a label or something?
Some little snippet that i use:
private void QuickStarter_Load(object sender, FormClosedEventArgs e)
{
button1.Text = Properties.Settings.Default.Button1;
}
Icon ico = null;
OpenFileDialog ofd = new OpenFileDialog();
string[] fileNames = new string[5];
private void application1ToolStripMenuItem_Click(object sender, EventArgs e)
{
ofd.Filter = "EXE|*.exe";
ofd.Title = "Add application";
if (ofd.ShowDialog() == DialogResult.OK)
{
ico = Icon.ExtractAssociatedIcon(ofd.FileName);
button1.Text = Path.GetFileNameWithoutExtension(ofd.FileName);
button1.Image = ico.ToBitmap();
button1.Enabled = true;
fileNames[0] = ofd.FileName;
}
}
private void button1_Click(object sender, System.EventArgs e)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = fileNames[0];
Process.Start(start);
}
private void QuickStarter_FormClosed(object sender, FormClosedEventArgs e)
{
Properties.Settings.Default.Button1 = button1.Text;
Properties.Settings.Default.Save();
}
}
Verifying the complaint
Using the following code works just fine for me, clicking the button will set the new text and closing and reloading the application will tell me when the button was last clicked.
private void Form1_Load(object sender, EventArgs e) {
button1.Text = Settings.Default.button1;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
Settings.Default.button1 = button1.Text;
Settings.Default.Save();
}
private void button1_Click(object sender, EventArgs e) {
button1.Text = string.Format("Button was clicked at {0}", DateTime.Now);
}
You might have a problem with your applications permissions, if it isn't allowed to write to the %appdata% subfolders it won't be able to store the settings.
But it's also entirely possible you have some other problem in your solution. One that isn't immediately clear from your description. Make a minimal test project (like i did) and verify that you can't save and retrieve settings on a brand new test project.
Answering your question
Whenever you ask something along the lines of What is the optimal way to ... you are not going to get a conclusive answer and if i know anything about Stack Overflow i would say it's discouraged when you ask your question.
That said, here's how i would have done it.
Create a collection of data objects that implements the Serializable attributes. See Introducing XML Serialization
That collection would hold properties that describe your buttons, the text, the executable and (if applicable) their position using a Point structure.
I would deserialize that on load and serialize it on close (or better yet, when something changes)
I would (after deserialization) iterate the data objects in that collection and dynamically create the buttons at runtime, adding them to the Form's Controls like so:
Controls.Add(new Button { Text = "This is a new button!"});
I would also add some controls to add/remove entries from your data object collection. Or by using a context menu, either way works. Your design, your decisions.
As you get more confident with your coding you can move on to dragging and dropping buttons to order them or position them in your 'quicklaunch' application.
You need to add the button1 property to the Settings in the Settings.Designer.cs (or use the Settings.settings grid.
You also need to make sure that the "QuickStarter_FormClosed" event is fired when you're window is closed.
This is my Settings.Designer.cs:
namespace SettingsSaveTest.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string ButtonText {
get {
return ((string)(this["ButtonText"]));
}
set {
this["ButtonText"] = value;
}
}
}
}
I didn't notice it was for Windows Forms, and not WPF, but the same thing applies, you need to add the property to your settings.designer.
Here is my version in Windows Forms:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
button1.Text = Properties.Settings.Default.button1;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
button1.Text = "Saving...";
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
SaveProperties();
}
private void SaveProperties()
{
Properties.Settings.Default.button1 = textBox1.Text;
Properties.Settings.Default.Save();
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = textBox1.Text;
}
}
I also added the FormClosed eventhandler to the FormClosed stack:
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed);
I am also leaving my answer for WPF, since some other people might wonder. But the same thing applies. You need to add the property, and configure the event listeners.
This is my MainWindow.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Button1.Content = Properties.Settings.Default.ButtonText;
Closed += SaveSettings;
}
private void SaveSettings(object sender, EventArgs e)
{
SaveProperties();
}
private void SaveProperties()
{
Properties.Settings.Default.ButtonText = UserInput.Text;
Properties.Settings.Default.Save();
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
SaveProperties();
Button1.Content = Properties.Settings.Default.ButtonText;
}
}
And finally my MainWindow.xaml
<Window x:Class="SettingsSaveTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox x:Name="UserInput" x:FieldModifier="public" HorizontalAlignment="Left" Height="23" Margin="48,105,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
<Button x:Name="Button1" Content="Button" HorizontalAlignment="Left" Margin="203,105,0,0" VerticalAlignment="Top" Width="75" Click="Button1_Click"/>
</Grid>
I am trying to create a series of buttons, each play a sound. This sound is retrieved from an OpenFileDialog function. However, I have encountered the issue of one sound being assigned to all of the buttons. I know why this occurring, but I am unsure of how to resolve the issue. Basically, I began by assigning the same algorithms to each button:
openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileName = openFileDialog.FileName;
}
And:
soundPlayer = new SoundPlayer(fileName);
soundPlayer.Play();
Unfortunately, this was extremely ugly and so I decided to put each algorithm in to a method and just call the methods to their respective buttons. Like so:
public void openDialog()
{
openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileName = openFileDialog.FileName;
}
}
private void button27_Click(object sender, EventArgs e)
{
openDialog();
}
public void playDialog()
{
soundPlayer = new SoundPlayer(fileName);
soundPlayer.Play();
}
private void button1_Click(object sender, EventArgs e)
{
playDialog();
}
However, because openDialog() calls the same variable which receives the file name, each of the buttons calling openDialog() is using the same variable and so playing the same sound.
You have to make the fileName "part" of the Button. You can do it by either:
Using the Tag property of a button and cast to string when retrieving
Create a subclass of a Button called SoundButton and add FileName property of type string
Make a pick.
For example, using a Tag:
public void playDialog(string fileName)
{
soundPlayer = new SoundPlayer(fileName);
soundPlayer.Play();
}
private void button1_Click(object sender, EventArgs e)
{
playDialog((sender as Button).Tag as string);
}
You can make a list of sounds and then play it in a loop one by one:
Creating the list:
List<string> soundsList = new List<string>();
Adding to the list:
sounds.Add(openFileDialog.FileName);
Playing sounds:
foreach(string sound in soundsList)
{
soundPlayer = new SoundPlayer(sound);
soundPlayer.Play();
}
My answer of course is assuming you keep an order of first adding all the sounds you want and then playing them all. You should of course also need to add validation to check that the user has given you a correct sound to add to the list.
EDIT:
After reading your comment, you can also add a sound to Tag property of the button. Then when you want to play a sound of a specific button, you can just play whatever is inside that property of the button.
For example you can override the Click event like this:
private void button_Click(object sender, EventArgs e)
{
string soundFile = (sender as Button).Tag as string;
playDialog(soundFile);
}
This way all sounds are a "part" of the button