Allow users to select and change icons in a multi company program - c#

I am developing a C# program that will allow the users to enter multiple companies, and I am trying to allow the users to use an icon (as well as the name of the company in the taskbar) for each company to help them differ easily between them.
So far I have the following code, which shows a picturebox of the icon to confirm it is the correct image, but when I run the program it crashes with an out-of-memory-exception after changing the image 3 or 4 times. After reading solutions to similar questions on this site I have tried to dispose the image but can't seem to get it to work correctly:
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.InitialDirectory = "R:\\rightsort fulfilment\\charity icons";
openFileDialog1.Title = "Choose an Icon";
openFileDialog1.FileName = "";
openFileDialog1.Filter = "Icon Files|*.ico";
if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
{
txtIcon.Text = openFileDialog1.FileName;
pictureBox1.Image = Image.FromFile(txtIcon.Text);
pictureBox1.Visible = true;
}
else
{
txtIcon.Text = "";
pictureBox1.Visible = false;
}
}
Any help would be greatly appreciated!

Image class inherited from IDisposable. You need to call Dispose method every time you replace it with new image to release resources.
However I don't know if this is the source of your problem. You also can try to run memory profiler and see where and how exactly memory gets allocated.

I would try disposing the old image in the picture control. Something like this:
if (openFileDialog1.ShowDialog() != DialogResult.Cancel)
{
txtIcon.Text = openFileDialog1.FileName;
Image oldImage = pictureBox1.Image;
pictureBox1.Image = Image.FromFile(txtIcon.Text);
if (oldImage != null)
{
oldImage.Dispose();
}
pictureBox1.Visible = true;
}

Related

OpenFileDialog and UnauthorizedAccessException

I'm developing a tool that processes an .fbx model and user input into a single file for use in a game. The code for when the user presses the "Import Model" button is as follows, and is similar for every button:
private void E_ImportModelButton_Click_1(object sender, EventArgs e)
{
E_model = null; // byte array where model is stored
E_SelectedFileLabel.Text = "No Model Selected"; // label on form
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "FBX Model (.fbx)|*.fbx";
ofd.Multiselect = false;
if (ofd.ShowDialog() == DialogResult.OK)
{
// adjusts variables for game file
string s = Path.GetDirectoryName(ofd.FileName);
E_model = File.ReadAllBytes(s);
E_SelectedFileLabel.Text = "File Selected: " + ofd.FileName;
}
}
The problem is, whenever I click OK, an UnauthorizedAccessException occurs. I have tried importing files from C:\Users\Owner\Downloads as well as C:\Users\Owner\Desktop and the C:\ drive itself, but it still occurs. What could I add to this code to gain access to these (and other) folders?
You are trying to read from directory via the method intended to read from a file:
string s = Path.GetDirectoryName(ofd.FileName);
E_model = File.ReadAllBytes(s);
Replace it with:
E_model = File.ReadAllBytes(ofd.FileName);
You can't ready the directory, you have to read a file:
string s = Path.GetDirectoryName(ofd.FileName);
E_model = File.ReadAllBytes(s);
Try adding the file name here

Executing another Application with selected file using a button (C# Programming)

To start, I'm a newbie with C# Programming and I've tried googling for solutions about my problem but it seems that i cannot find one, or simply too unlucky or too blind to spot one. I'm using Microsoft Visual Studio 2005.
Anyways. I was assigned to modify/create an automated test environment input application. The said application already has a function to run/start a CANoe program with a pre-defined file or if it's already running, stop the program.
private void button1_Click(object sender, EventArgs e)
{
// Execute CANoe(Obtain CANoe application objectg)
mApp = new CANoe.Application();
mMsr = (CANoe.Measurement)mApp.Measurement;
try
{
mApp.Open("C:\\Users\\uidr3024\\Downloads\\SRLCam4T0_Validation_ControlTool\\cfg\\SVT_SRLCam4T0_025B.cfg", true, true);
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
// Finish CANoe
if (mApp != null) {
mApp.Quit();
}
// Release the object
fnReleaseComObject(mMsr);
fnReleaseComObject(mApp);
}
What I wanted to do now is to have an OpenFileDialog box that will show a selection of files and user will be able to browse and select any file to start the CANoe program with the selected file and not just the file path that's been input in the code along the "mApp.Open()" syntax. I've tried this:
private void button5_Click_1(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\Users\uidr3024\Downloads\SRLCam4T0_Validation_ControlTool\cfg";
openFileDialog1.Title = "Browse Configuration Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.Filter = "CANalyzer/CANoe Configuration (*.cfg)|*.cfg |All files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}
}
I've tried this code that I often see in the Web and in the Tutorials but I don't know how to incorporate it with the button for running the CANoe program so that when user clicks the Open button from the Dialog Box, the file path would be shown in the textbox(optional) and/or when the user then clicks the Start CANoe, CANoe program would start with the selected .cfg file.
Am I making any sense here? Or am I doing the right thing here?
Btw, I found these... And I'm using a CANoe library for these, ofc.
#region "***** CANoe Object definition *****"
private CANoe.Application mApp = null; // CANoe Application CANoeƒAƒvƒŠƒP[ƒVƒ‡ƒ“
private CANoe.Measurement mMsr = null; // CANoe Mesurement function CANoe‘ª’è‹#”\
private CANoe.Variable mSysVar = null; // System variable ƒVƒXƒeƒ€•Ï”
private CANoe.Variable mSysVar_start = null; // System variable ƒVƒXƒeƒ€•Ï”
#endregion
I think you have done most of the hard work, unless I've missed something I think you just need something like this in your button1_Click method:
if( textBox1.Text != String.Empty && System.IO.File.Exists(textBox1.Text) )
{
// The textbox has a filename in it, use it
mApp.Open(textBox1.Text, true, true);
}
else
{
// The user hasn't selected a config file, launch with default
mApp.Open("C:\\Users\\uidr3024\\Downloads\\SRLCam4T0_Validation_ControlTool\\cfg\\SVT_SRLCam4T0_025B.cfg", true, true);
}

Open File Dialog box on Clicking Link Label

I've created a log in panel in which I've used Transparent group box(with user name text box and password text box), and used a wallpaper on background, now I've Used a link label on this log in panel by clicking on which the user can change the background wallpaper of the log in panel.
Means when user clicks on the link label (lnklblChangeBackGround) with text "Click Here to Change Background" open dialogue box will open and user can select the Wallpaper from here and then by clicking on OK or Select the wallpaper will be assigned to background of the log in panel
Can any one help me out that
how can i open a open dialogue box by clicking on the link label
how can i assign a select wallpaper to the background of my log in panel
Note: I'm Creating this using VS 2010 using C#. and it's a desktop App and i'm using winform here.
At first you have to add an Event (LinkClicked) to your Link Label.
Just place this code here to open a file dialog.
private String getPicture()
{
string myPic = string.Empty;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "jpg (*.jpg)|*.jpg|png (*.png)|*.png";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
myPic = openFileDialog1.FileName;
return myPic;
}
You can edit the filter to avoid the user choosing images, which is not supported in your opinion.
With this code below you can set the Background Image of your pictureBox
private void setBackground(String picture)
{
pictureBox1.Image = null;
pictureBox1.Image = Image.FromFile(picture);
}
And the final version would look like this
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
String myFile = getPicture();
setBackground(myFile);
}
if this is too much code or too complicated for you, then you can just put it all in one function like this
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string myPic = string.Empty;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "jpg (*.jpg)|*.jpg|png (*.png)|*.png";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
myPic = openFileDialog1.FileName;
pictureBox1.Image = null;
pictureBox1.Image = Image.FromFile(myPic);
}

C# After using OpenFileDialog, a MessageBox doesn't open on top

Our primary database application has a feature that exports either an Excel workbook or an Access mdb for specified work orders. Those files are then sent to our subcontractors to populate with the required data. I am building an application that connects to the files and displays the data for review prior to being imported into the primary database. Simple enough, right? Here’s my problem: the application opens a OpenFileDialog box for the user to select the file that will be the datasource for the session. That works perfectly. If I open a MessageBox after it, that box open up behind any other open windows. After that, they respond correctly. I only expect to be using MessageBoxes for error handling, but the problem is perplexing. Has anyone encountered this problem?
The MessageBoxes in the code are only to verify that the path is correct and to solve this problem; but, here’s my code:
private void SubContractedData_Load(object sender, EventArgs e)
{
string FilePath;
string ext;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Microsoft Access Databases |*.mdb|Excel Workbooks|*.xls";
ofd.Title = "Select the data source";
ofd.InitialDirectory = ElementConfig.TransferOutPath();
if (ofd.ShowDialog() == DialogResult.OK)
{
FilePath = ofd.FileName.ToString();
ext = FilePath.Substring((FilePath.Length - 3));
if (ext == "xls")
{
MessageBox.Show(FilePath);
AccessImport(FilePath);
}
else if (ext == "mdb")
{
MessageBox.Show(FilePath);
AccessImport(FilePath);
}
}
else
{
System.Windows.Forms.Application.Exit();
}
}
While it isn't advisable to use MessageBoxes to debug your code, I think the immediate problem is that you are doing this in the form's load event.
Try it like this:
protected override void OnShown(EventArgs e) {
base.OnShown(e);
// your code
}
Your problem is definitely the fact that you're trying to do this while loading the Form, because the form isn't yet displayed.
Another alternative would be moving this functionality out of the Load event and give the user a button to push or something like that.
In other words:
private void SubContractedData_Load(object sender, EventArgs e)
{
// unless you're doing something else, you could remove this method
}
Add a button that handles this functionality:
private void SelectDataSourceClick(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Microsoft Access Databases |*.*|Excel Workbooks|*.xls";
ofd.Title = "Select the data source";
ofd.InitialDirectory = ElementConfig.TransferOutPath();
if (ofd.ShowDialog() == DialogResult.OK)
{
var FilePath = ofd.FileName.ToString();
var ext = Path.GetExtension(FilePath).ToLower();
switch (ext)
{
case ".xls":
MessageBox.Show(FilePath);
AccessImport(FilePath);
break;
case ".mdb":
MessageBox.Show(FilePath);
AccessImport(FilePath);
break;
default:
MessageBox.Show("Extension not recognized " + ext);
break;
}
}
else
{
System.Windows.Forms.Application.Exit();
}
}

Save Image to particular folder from Openfiledialog?

I want to save images to my project folder from openfiledialog result . I don't get foler path to save . How do I get folder path ? How do I save that ? Please Help me.
FileDialog.FileName gives the full path to the file. And btw it is probably easier to use the SaveFileDialog because you want to save something, not open.
Hello thinzar,
private void button2_Click(object sender, EventArgs e)
{
Bitmap myBitmap = new Bitmap();
this.saveFileDialog1.FileName = Application.ExecutablePath;
if (this.saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
myBitmap.Save(this.saveFileDialog1.FileName);
}
}
Bye
The System.Windows.Forms.FolderBrowserDialog allows the user to select a folder. Maybe that would be a better option?
Something alone these lines
Bitmap myImage = new Bitmap();
// draw on the image
SaveFileDialog sfd = new SaveFileDialog ();
if(sfd.ShowDialog() == DialogResult.OK)
{
myImage.Save(sfd.FileName);
}
I guess you're opening a file elsewhere and then using the results to later save stuff into the directory you opened from?
DialogResult result = OpenFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string directoryName = Path.GetDirectoryName(OpenFileDialog1.FileName);
// directoryName now contains the path
}

Categories