Opening Image directly into program - c#

I made a basic picture viewer program in C# windows from , following a tutorial.
The program works fine but I want to open it like default windows photo viewer. I tried to open an image with the program directly but that opened the program and the image box was empty.
The image box works fine when images are browsed to open inside the program but how to make it work externally?
Extra : And is there a way to make it full screen?
Sorry for bad english.
P.S: Consider me very noob when helping. Thank you :)
namespace Basic_Picture_Viewer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void showButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Load(openFileDialog1.FileName);
}
}
private void clearButton_Click(object sender, EventArgs e)
{
pictureBox1.Image = null;
}
private void backgroundButton_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.BackColor = colorDialog1.Color;
}
}
private void closeButton_Click(object sender, EventArgs e)
{
ActiveForm.Close();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
else
pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void rotateButton_Click(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
Image img = pictureBox1.Image;
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox1.Image = img;
}
}
}

Okay, so in your Program.cs file, implement the commmand line arguments according to the link in the comment above, and pass it to the form.
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if(args.Length > 0)
Application.Run(new Form1(args[0]));
else
Application.Run(new Form1());
}
Then in your form, change the constructor to
public Form1(String fileName = null)
{
InitializeComponent();
if (fileName != null)
{
// Add validation to ensure file exists here
this.WindowState = FormWindowState.Maximized;
pictureBox1.Load(fileName);
}
}
You'll either want a try/catch block or something to check for the existence of the file before attempting to open it. Under the use case you describe I would consider a missing file an exceptional case, so that seems like a plan to me.

The statement public Form1(String fileName = null) specifies one optional argument.Optional arguments are arguments that have a default value in the function,you always have the option to either call the function with or without argument,if you specify any argument the new argument is used in place of default argument,and in case you don't specify an argument when calling the function the default argument is used.The default value to optinal argument must always be a value that is a constant at compile time.To better clarify that let me take an example.Consider we have a function that adds two numbers.
private int AddNumbers(int a=10,int b=15)
{
int c=a+b;
return c;
}
We have specifies two optional arguments for the function,the above functions doesn't flag any error but as I said optional arguments must have a default value which is know at design time so the function below flags an error that follows Default parameter values must be compile time constant. because it uses default values that will be known at runtime.
int z,x;
private int AddNumbers(int a=z,int b=x)
{
int c=a+b;
return c;
}
Consider that the variables z and x are calculated using some logic at runtime,but are not unknown at compile time.This would flag the error.
Next,let me tell you differences in a normal function and a functional with optional parameters.The first function that compiles with no errors can be called in two ways;
**By passing some arguments when calling**
AddNumbers(5,15);
This will return 20.
**By calling the function without specifying any arguments**
AddNumbers();
This will return 25,remember we defined 10,15 as default arguments.Both the calls are valid and will compile without any errors.
So now I hope you've found answer to your question,if you would like to read more have a look here.

Related

C# Localization from one Form for all other forms opened in the program

to me, the question in the title seems like a regular thing one might do or have problems with, but I could not find anything on that matter.
I wrote a small program for a machine that I'm building and want to translate the UI-Elements, warning messages etc. into different languages. (German and English to start with). For that, I want to set the language in a "Settings"-form with a dropdown combobox.
I already found a working example on here how to do general localization of a form, and VisualStudio does not make it fairly difficult. How do I proceed from here? Do I need to pass some variable to the form I open, or can I set the language as a global variable and load it while opening other new forms.In total there are like 6 or 7 forms that will be opened and closed during usage.
Example code of two forms:
namespace Test
{
public partial class MES : Form
{
public MES()
{
InitializeComponent();
}
private void Messen_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("English");
comboBox1.Items.Add("Deutsch");
comboBox1.SelectedIndex = 0;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.ToString() == "English")
{
ChangeLanguage("en");
}
else
{
ChangeLanguage("de-DE");
}
}
private void ChangeLanguage(string lang)
{
foreach (Control c in this.Controls)
{
ComponentResourceManager resources = new ComponentResourceManager(typeof(Messen));
resources.ApplyResources(c, c.Name, new CultureInfo(lang));
}
}
private void button2_Click(object sender, EventArgs e)
{
NewForm NF = new NewForm();
NF.Show();
this.Close();
}
}
Changing the label and button names in the MES Form does work, but nothing changes in the NF form (Localization is set to true there as well, and languages set accordingly).
Thanks for any hints and tips in advance.
Use the below method . Source StackOverflow
You can Pass this as reference in the localizeForm.
private static void localizeForm(Form frm) {
var manager = new ComponentResourceManager(frm.GetType());
manager.ApplyResources(frm, "$this");
applyResources(manager, frm.Controls);
}
private static void applyResources(ComponentResourceManager manager, Control.ControlCollection ctls) {
foreach (Control ctl in ctls) {
manager.ApplyResources(ctl, ctl.Name);
applyResources(manager, ctl.Controls);
}
}

C# Input string Error

I'm trying too get the users value entered and count down in seconds from it, but whenever I input anything and click the start button it says input string not in correct format. I've googled and googled and cannot figure out how to get the users input and parse or convert it into an int and countdown from it, whilst updating the label via timer of course.
I'm use to console applications still wrapping my head around the syntax...
using System;
using System.Windows.Forms;
namespace Countdown {
public partial class Form1 : Form
{
int seconds; string user; int test = 30;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void tmrCountdown_Tick(object sender, EventArgs e)
{
lblDisplay.Text = test.ToString();
if (test > 1)
{
lblDisplay.Text = test.ToString() + " Seconds Remaining";
}
else if (test == 1)
{
lblDisplay.Text = test.ToString() + " Second Remaining";
}
else
{
tmrCountdown.Stop();
}
test--;
}
public void btnStart_Click(object sender, EventArgs e)
{
int test = int.Parse(txtBoxInput.Text);
tmrCountdown.Start();
}
private void txtBoxInput_TextChanged(object sender, EventArgs e)
{
}
}
}
Error is at "int test = int.Parse(txtBoxInput.Text);"
Change Parse into TryParse and see what value can't be parsed:
public void btnStart_Click(object sender, EventArgs e)
{
if (int.TryParse(txtBoxInput.Text, out test))
// We succeed in parsing, so we continue with the timer
tmrCountdown.Start();
else {
// We failed in parsing
// Let's put keyboard focus on the problem text box...
if (txtBoxInput.CanFocus)
txtBoxInput.Focus();
// ... and report what's been happened
MessageBox.Show($"'{txtBoxInput.Text}' is not a valid integer value",
Application.ProductName,
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
There are two problems in your code.
The first one is the fact that you don't protect your code from invalid inputs. If you don't type something in the txtBoxInput or if you type text that cannot be converted to an integer you get the Invalid String Format Exception
The second problem is the variable test. You declare it locally inside the button click and given the fact that you don't get compilation errors then you are not setting the global class level variable with the same name that you are using in the timer Tick event.
So, use TryParse everytime you need to handle user inputs. This will not raise an exception in case of problems, but just return true or false. Finally do not re-declare the int test variable inside the button click, but use the global class level variable directly in the output of TryParse
public void btnStart_Click(object sender, EventArgs e)
{
// Try to convert the input in an integer. If this succeed you have
// the global variable _test_ set to converted text
if(!Int32.TryParse(txtBoxInput.Text, out test)
MessageBox.Show("Invalid input. Please type a number!");
else
tmrCountdown.Start();
}
try this code at your button
int test=Convert.ToInt32(txtBoxInput.Text);
tmrCountdown.Interval = test*1000; //have to multiply to 1000 since timer interval value is in milliseconds.
tmrCountdown.Start();
Just put integers in your textbox

System.FormatException occurred in mscorlib.dll when converting it int32

I know, i know there are lots and lots of questions asking on here about this error, each with their own response, but its easier to work off a response regarding your own code rather than someone else's
I have been working on this program for some time for a college assignment, and as soon as i started putting in the class to calculate the totals of things it now crashes,
I don't know where to look so i'll post my main code
enter code here
namespace Till
public partial class MainWindow : Window
{
Calculator calc = new Calculator();
public MainWindow()
{
InitializeComponent();
}
public bool User;
public bool tillopen = false;
private void button_Click(object sender, RoutedEventArgs e)
{
//button clone thingy
Button btn = (Button)sender;
label.Content = label.Content + btn.Content.ToString();
Console.Beep(); // makes the buttons beep
}
private void clear_Click(object sender, RoutedEventArgs e)
{
// Clear
label.Content = "";
}
private void Button_Submit_Click(object sender, RoutedEventArgs e)
{
// submit
listView.Items.Add(label.Content);
label.Content = "";
calc.setSoldItems(Convert.ToInt32(label.Content)); /// it breaks on this line///
}
private void button13_Click(object sender, RoutedEventArgs e)
{
//void sale
label.Content = "";
listView.Items.Clear();
}
private void button15_Click(object sender, RoutedEventArgs e)
{
//pound
label.Content = "1.00";
}
private void button12_Click(object sender, RoutedEventArgs e)
{
//till open close
tillopen = true;
}
private void button16_Click(object sender, RoutedEventArgs e)
{
Login m = new Login();
m.Show();
this.Close();
}
private void button14_Click(object sender, RoutedEventArgs e)
{
label.Content = "2.00"; // 2 pound
}
private void button17_Click(object sender, RoutedEventArgs e)
{
label.Content = calc.finish();
}
}
I have tried to re-create the error in another WPF (converting a to an int32) and it works fine, i know this is an issue with my code itself, i have tried using other machine and using different versions of visual studio itself, so we came to the assumption its this code itself and not a broken dll file
So before I sit down with my Teacher and spend all day going though my code step by step im asking around for help in order to save both of our time, This assignment is due in in 3 weeks, and it decides to break on me now.
thankies
To replicate this error, i press a number button on my Windows form, them hit the submit button i created (which starts the conversion) If a copy of my class which handles all of this is needed im happy to post it
In the method button_click, you have assigned value as
label.Content = label.Content + btn.Content.ToString();
which is a string value to the label and the values are concatenated instead of add.
and when you are reading it, you are converting it in Int32. which will give exception as it will not contain any integer value to it.
You can add the value like this:
label.Content = (Convert.ToInt32(label.Content) + Convert.ToInt32(btn.Content)).ToString();
and check before converting if the label has blank values in it, if it has do not convert them, and only convert the value if it has some values it will not give any error. Also do not assign any values other that numerical digits.
You are calculating:
Convert.ToInt32(label.Content)
but on the line before you set:
label.Content = "";
so this means you are calculating
Convert.ToInt32("")
which gives you a FormatException.
Perhaps you should use the value of label.Content before you overwrite it?

overloaded method match has some invalid arguments

I keep getting this error - The best overloaded method match for HomeInventory2.Form1.Form1(System.Collections.Generic.IEnumerable) has some invalid arguments - for the starred section. At the same time I am also getting this error in the same spot - Argument 1: cannot convert from 'string' to System.Collections.Generic.IEnumerable
**Sorry - I should have added, the code sends a string to another form where it is split up and placed into separate text boxes.
namespace HomeInventory2
{
public partial class Form2 : Form
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, System.EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Run**(new Form1(richTextBox1.Text))**;
}
}
}
First off, you probably don't want to call Application.Run here - you already have a form.
I suspect you want to split the rich text box content by lines, then pass this to the new form and show it. If that is the case, you can do:
private void button2_Click(object sender, EventArgs e)
{
// richTextBox1.Lines is a string[], which works with IEnumerable<string> (per line)
var form = new Form1(richTextBox1.Lines);
// Just show the form
form.Show();
}

Making two boxes equal each other

I am trying to make a text box (UPC_txtBox4) self populate to equal the same value of UPC_txtBox2. The two text boxes are on separate forms but I feel there should be a way to link the two.
If form1 is responsible for navigating to form2, then you can pass the value on the query string from form1 using a URL similar to the following:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Response.Redirect(Request.ApplicationPath + "/Form2.aspx?upc=" + UPC_txtBox2.Text, false);
}
}
then in form2 code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Assuming this field is an asp.net textbox and not an HTML input
UPC_txtBox4.Text = Request.QueryString["upc"];
}
}
Alternatively, you could store the value in session state, assuming that you are using sessions.
CORRECTION: Seeing as you are using WebForms, not WinForms as I had assumed, the below is irrelevant. I'll leave it just incase it helps someone else.
You should just create a method on the form that needs to be updated, then pass a reference when of that form to the newly created form.
This won't work if either form is a dialog (as far as I know).
So:
Form that has the textbox that will be directly edited.
private Form formToUpdate;
public void OpenForm(Form _formToUpdate)
{
formToUpdate = _formToUpdate;
txtBlah.TextChanged += new EventHandler(OnTextChanged);
this.Show();
}
private void OnTextChanged(object sender, EventArgs e)
{
formToUpdate.UpdateText(txtBlah.Text);
}
Form that is to be dynamically updated:
delegate void StringParameterDelegate (string value);
public void UpdateText(string textToUpdate)
{
if (InvokeRequired)
{
BeginInvoke(new StringParameterDelegate(UpdateText), new object[]{textToUpdate});
return;
}
// Must be on the UI thread if we've got this far
txtblah2.Text = textToUpdate;
}
Note: this is untested (although it should work), and largely pseudo code, you'll need to tailor it to your solution obviously.

Categories