I am trying to create a MessageBox that appears at the start of my program, asking the user if they would like to load a file or not. So far I have:
public static void LoadFile(object sender, FormClosingEventArgs e)
{
System.Windows.MessageBox.Show("Would you like to load a file?",
System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxQuestion);
if (result == DialogResult.No)
{
// cancel the closure of the form.
e.Cancel = true;
}
}
I realize that some of this code is used to exit out of the program. I don't intend to do this, it is just currently still left in from the sample code I was trying. When I try this code, I receive several errors, the major one involves the MessageBoxQuestion. The error reads
The type or namespace name 'MessageBoxQuestion' does not exist in the namespace System.Windows
I previously had this error on the MessageBoxButtons but fixed it by changing it to MessageBoxButton. Starting with just a simple message box, I originally had the code:
public static void LoadFile()
{
System.Windows.MessageBox.Show("Text");
}
This worked perfectly fine, despite the fact that I had to add the System.Windows. to remove the error
The name MessageBox does not exist in the current context.
Does anyone know a solution as to how I can get my MessageBox working correctly?
The WPF version of MessageBox differs from the Windows Forms' version. You need to use this overload.
Here is what I finally came up with:
public static void LoadFile()
{
// Configure message box
string message = "Would you like to load a file?";
string caption = "Startup";
System.Windows.MessageBoxButton buttons = System.Windows.MessageBoxButton.YesNo;
System.Windows.MessageBoxImage icon = System.Windows.MessageBoxImage.Information;
// Show message box
System.Windows.MessageBoxResult result =
System.Windows.MessageBox.Show(message, caption, buttons, icon);
if(result == System.Windows.MessageBoxResult.Yes)
{
}
else if(result == System.Windows.MessageBoxResult.No)
{
}
}
I included the if else branch that I planned to use later.
Related
I have a WPF app that will be acting like a desktop, with certain apps available, such as Microsoft Edge browser. I am able to open multiple windows of it, add a button to a custom taskbar, but the problem is, you could find the process by name, but then the buttons/program doesnt know which correct window to open. And if I search by ID, VS gives me:
System.ArgumentException:'Process with an Id of #### is not running'
Since Microsoft it self, changes the ID of the initial ID that it starts with.
So the methods right now im using for trying to get the right window is:
public void NewTabClick(object sender, RoutedEventArgs e)
{
//NewTabClick is a click event that gets created with every new button
MessageBox.Show("NewTabClicked");
ShowWindow(GetWindowHandle(), 3);
}
private IntPtr GetWindowHandle()
{
try
{
//Here is where i get the exception error
return Process.GetProcessById(ProcessId).MainWindowHandle;
}
catch (NullReferenceException)
{
return IntPtr.Zero;
}
}
ProcessId is set when we start the app itself in another method like this
private void StartApp()
{
var process = Process.Start(ProgramPath);
SetProcessId(process);
}
private void SetProcessId(Process process)
{
ProcessId = process.Id;
}
Is there a way to keep track/change/update which ID it should look for, or another way to keep track of these windows/browsers?
Thanks in advance!
I have a common dialog opened like this:
private void SaveLogButton_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog dialog = new SaveFileDialog
{
Filter = #"Text file|*.txt",
Title = #"Save to...",
};
if (dialog.ShowDialog()== DialogResult.OK)
{
// Do some job
}
}
catch (Exception ex)
{
// Handle some errors
}
}
Sometimes, however, (with like 10% probability) ShowDialog() method does not show the dialog itself, though I can see it's parent form, which i can't click too (error sound appears). The only thing that helps here is CtrlAltDel.
No exceptions trigger, and debug wont go after ShowDialog line. Any suggestions?
Thank you.
Short addition: I'm working on an Excel Add-In using WinForms.
Use this 'ShowDialog' overload https://msdn.microsoft.com/en-us/library/9a55b9ds(v=vs.110).aspx to specify Owner.
if (dialog.ShowDialog(this)== DialogResult.OK)
I just added the feature where I can make my program the default-program for multiple music filetypes by following this question on Stackoverflow
It seemed to work fine, since all of the mp3 files etc has my icon on them in Explorer.
But when I tried starting one (I have handled the arguments just fine) the process itself starts (it shows up in Task Manager) but nothing happens. I even tried adding a Messagebox in the beginning of the "Window.Initialized"-event, but no messagebox came up.
What might be the cause of this problem? I have literally no idea what's wrong.
If you need code or anything, just ask for it since I don't know what to include in this question.
Thank you.
Here's the code for Window_Initialied
private void Window_Initialized(object sender, EventArgs e)
{
MessageBox.Show("asd");
HandleInstances(); // Checks if multiple instances of the program is running. Exits it if there's more than one instance (tried commenting this out, didn't work)
if (Properties.Settings.Default.HasRegisteredFiletypes == false) // Checks if theres a need to add the filetypes
AddExec();
StartWithMusic(Environment.GetCommandLineArgs().ToList()); // Here I call for the arguments. Checks if there are valid files in the arguments (.mp3, .flac etc)
SettingsLoadBGs.IsChecked = Properties.Settings.Default.LoadBGs;
// set accentcolor box
List<AccentColor> ac = new List<AccentColor>();
string userAccent = Mplayer.Properties.Settings.Default.Accent.ToLower();
foreach (Accent c in ThemeManager.DefaultAccents)
{
AccentColor acEnt = new AccentColor();
acEnt.Name = c.Name;
ac.Add(acEnt);
if (c.Name.ToLower() == userAccent)
ThemeManager.ChangeTheme(this, c, Theme.Dark);
}
ThemeManager.IsThemeChanged += new EventHandler<OnThemeChangedEventArgs>(ThemeChanged);
accentChooserBox.ItemsSource = ac;
}
Im currently facing the problem that when i try to set focus on some control (textBox), nothing happens, maybe i just overlooked something.(somewhere i found that focus is "low-level" method and that select() should be used instead, however, it doesnt work as well)
From form Login, i launch new instance of EncryptPSW form
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
EncryptPSW ePSW = new EncryptPSW();
ePSW.setOsLog(false, this);
ePSW.ShowDialog();
}
On Button(which is located on EncryptPSW form ) click event i call fill method
public void fill()
{
if (textBoxPSW.Text.Length == 8)//psw has to be 8 chars long
{
if (save)//determinating whether save or fetch of data should be done
{ login.launchSave(textBoxPSW.Text,this); }
else { login.launchOpen(textBoxPSW.Text,this); }
}
else { MessageBox.Show("The password must contain 8 characters");}
}
Which launches either save or open method from Login (my problem is just with open, since during save i dont need to do anything with Focus)
public void launchOpen(string psw,EncryptPSW ePSW)
{
ePSW.Close();
Encryptor.DecryptFile("loggin.bin", psw, this); //decrypting data and setting textBoxes Text property into the fetched ones
setFocus();
}
After all the work is done, setFocus() should be called in order to set focus and other properties.
public void setFocus()
{
textBoxDatabase.Focus();
textBoxDatabase.SelectionStart = textBoxDatabase.TextLength - 1;
textBoxDatabase.SelectionLength = 0;
}
I tried so many different ways, like:
Calling setFocus() from within EncryptPSW_FormClosed
Calling whole open process after the EncryptPSW is closed (from within EncryptPSW_FormClosed)
and many more, however i dont remember it all.
In the case of Form_Closed the weird thing is, that when i tried to show a message box from there instead of setting focus (just to see where the problem might be), it's showed before the EncryptPSW form is closed.
My only guess about this is that the instance of EncryptPSW is somehow blocking Login form and it's controls
I hoped i described my problem well enough and that it makes at least a bit of sense ;]
Thanks in advance,
Regards,
Releis
Since the textbox is in the login form, and you are opening the EcryptPWS from it as a dialog (child), your login form will not be able to set focus to anything. You will need to set focus after it is closed. You can do this:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
using(EncryptPSW ePSW = new EncryptPSW())
{
ePSW.setOsLog(false, this);
if (ePSW.ShowDialog() == DialogResult.OK)
{
textBoxDatabase.Focus();
}
}
}
public void launchOpen(string psw,EncryptPSW ePSW)
{
ePSW.DialogResult = DialogResult.OK;
ePSW.Close();
Encryptor.DecryptFile("loggin.bin", psw, this); //decrypting data and setting textBoxes Text property into the fetched ones
}
OK this maybe the ugliest thing I saw round this but.
using
public void setFocus()
{
textBoxDatabase.Focus();
textBoxDatabase.SelectionStart = textBoxDatabase.TextLength - 1;
textBoxDatabase.SelectionLength = 0;
}
Change your code at
public void launchOpen(string psw,EncryptPSW ePSW)
{
ePSW.Close();
Encryptor.DecryptFile("loggin.bin", psw, this); //decrypting data and setting textBoxes Text property into the fetched ones
setFocus();
}
to
delegate void settingfocus();
public void launchOpen(string psw,EncryptPSW ePSW)
{
ePSW.Close();
Encryptor.DecryptFile("loggin.bin", psw, this); //decrypting data and setting textBoxes Text property into the fetched ones
settingfocus sf = new settingfocus(setFocus);
this.BeginInvoke(sf);
}
This worked for me
(Sorry for apparently thinking insert "this" before procedure, and change line x to this was legable)
So I'm trying to make a folderbrowser for my custom application in C# and the folderbrowser thing is okay, but I want to set it up like how the default one acts.
According to #Kevin I am trying to make a modal dialog.
// I create the folderbrowser control and await the directory
string CreateFileDialog(bool allowFixedDrives)
{
FolderBrowser fb = new FolderBrowser(this, allowFixedDrives);
fb.Show();
//return THE_SELECTED_FOLDER_DIR;
return "";
}
So in the folderbrowser there is a boolean to allow fixed drives and also a reference to the parent form:
// Create the control and receive whether or not it should read fixed drives and also get a reference to the parent control.
public FolderBrowser(Form1 frm1, bool allowFixed)
{
InitializeComponent();
this.allowFixed = allowFixed;
frm1.Enabled = false;
}
I freeze the main form when this dialog is created. If the user closes the form, it will return null or "" and if the user presses okay, it should return the selected directory (where THE_SELECTED_FOLDER_DIR is).
Does anyone know how I can cleanly implement a dialog that sends feedback to the parent form?
Feel free to ask if you are as confused as I am :)
So after a rather interesting discussion with #Kevin, I've decided that the best way to go about this would be to call a public function in the form and then show it. Kinda hard to explain, so I'll show you:
NB: I think this should be kept open just in case someone has the same issues I did...
So I want to simply get a selected folder name and I'll display that selected folder on a text control for example:
bool invalid = false;
string value = CreateFileDialog(true, out invalid);
if (!invalid)
{
txt_File.Text = value;
}
else
{
MessageBox.Show("A folder was not selected.");
}
Okay, so I'm creating a dialog. I check if the dialog was closed without selecting a file and display a messagebox if it's invalid....
string CreateFileDialog(bool allowFixedDrives, out bool invalid)
{
FolderBrowser fb = new FolderBrowser(this, allowFixedDrives);
return fb.ShowForm(out invalid);
}
Now here is where it gets interesting. I create the dialog here and call a function on the form to actually show it, but I pass a boolean as an out variable to detect if it was closed without selecting a file.
And finally:
public string ShowForm(out bool a)
{
ShowDialog();
frm1.Enabled = true;
if (!Directory.Exists(selectedFolder))
{
a = true;
return selectedFolder;
}
else
{
a = false;
return selectedFolder;
}
}
I return the selected folder name if the user pressed OK, otherwise don't return it and also set the out parameter to false.
There you have it.
I'd like to thank everyone who pitched in here, namely #Kevin.