Sandip's Programming Zen

An attempt to share tech/coding experiences

Posts Tagged ‘WinForms

Solution: Problem of focus when opening a Winform using Treeview node click

leave a comment »

I must blog this , since I could not find the fix as quickly as I should. So…
When you try to open a winform using treeview node selection (using any event like mouse_click on after_select) , the form opens, but it remains minimized even if you have set the focus and windowstate properties.  That is because treeview regains control after opening form, however there is no direct fix.  You can fix it by delaying the action of the event.

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.BeginInvoke(new TreeViewEventHandler(delayedClick), sender, e);
        }

        private void delayedClick(object sender, TreeViewEventArgs e)
        {
             // your code goes here…
        }

Original solution here.

Written by Sandip

January 6, 2011 at 4:12 pm

Posted in .Net

Tagged with

C# Winforms: Sending an email with attachment

leave a comment »

Sending an email from C# winforms application is exactly same as we do in webapps using System.Net.Mail namespace. Here is a sample code which sends out an email with an attachment (again it is not specific to winforms can be used in webapps as it is).

MailMessage msg = new MailMessage();
SmtpClient client;
Attachment attach = new Attachment(filepath);

if (varEmailID.IndexOf(',') > 0)
{
    string[] iDs;
    iDs = varEmailID.Split(',');
    for (int i = 0; i <= iDs.Length - 1; i++)
    {
        msg.To.Add(new MailAddress(iDs.GetValue(i).ToString()));
    }
}
else
{
    msg.To.Add(new MailAddress(varEmailID));
}

msg.Attachments.Add(attach);
msg.Subject = varSubject;
msg.Body = varBody;
msg.IsBodyHtml = false;
msg.Priority = MailPriority.Normal;

string FromEmail = ConfigurationSettings.AppSettings["SystemMailID"];
string SmtpServer = ConfigurationSettings.AppSettings["SmtpServer"];
string UserName = ConfigurationSettings.AppSettings["UserName"];
string Password = ConfigurationSettings.AppSettings["Password"]; 
client = new SmtpClient(SmtpServer);
client.UseDefaultCredentials = false;
System.Net.NetworkCredential creds = new System.Net.NetworkCredential(UserName, Password);
client.Credentials = creds;

msg.From = new MailAddress(FromEmail);

client.Send(msg);

Written by Sandip

October 17, 2009 at 4:22 am

Posted in .Net, Programming

Tagged with ,

C# : Resize image in Picture Box for Best fit

with 3 comments

Got a useful piece of here which I have implemented in following way to make a image preview form.

private void frmPreview_Load(object sender, EventArgs e)
{
try
{

pboxMain.Image = Image.FromFile(_imagePath);
pboxMain.Tag = Image.FromFile(_imagePath);
}
catch(Exception ex)
{
Log.Error(ex);
}
}

private void btFit_Click(object sender, EventArgs e)
{

if (btFit.Text == “Fit to Screen”)
{
handleFitToWindow(true);
btFit.Text = “Actual Size”;
}
else
{
handleFitToWindow(false);
btFit.Text = “Fit to Screen”;
}

}

private void handleFitToWindow(bool doFit)
{
try
{
/* Don’t perform any operation if no image is loaded. */
if (this.pboxMain.Tag != null)
{
if (doFit)  /* We’re fitting it to the window, and centering it. */
{
/* Create a temporary Image.

* Always work from the original image, stored in the Tag.
*/

Image tempImage = (Image)this.pboxMain.Tag;

/* Calculate the dimensions necessary for an image to fit. */
Size fitImageSize = this.getScaledImageDimensions(
tempImage.Width, tempImage.Height, this.pboxMain.Width, this.pboxMain.Height);

/* Create a new Bitmap from the original image with the new dimensions.

* The constructor for the Bitmap object automatically scales as necessary.
*/

Bitmap imgOutput = new Bitmap(tempImage, fitImageSize.Width, fitImageSize.Height);

/* Clear any existing image in the PictureBox. */
this.pboxMain.Image = null;

/* When fitting the image to the window, we want to keep it centered. */
this.pboxMain.SizeMode = PictureBoxSizeMode.CenterImage;

/* Finally, set the Image property to point to the new, resized image. */
this.pboxMain.Image = imgOutput;
}

else  /* Restore the image to its original size */
{
/* Clear any existing image int he PictureBox. */
this.pboxMain.Image = null;

/* Set the resize more to Normal; this will place the image

* in the upper left-hand corner, clipping the image as required.
*/

this.pboxMain.SizeMode = PictureBoxSizeMode.Normal;

/* Finally, set the Image property to point to the original image. */
this.pboxMain.Image = (Image)this.pboxMain.Tag;
}
}
}
catch (System.Exception e)
{
Console.WriteLine(e);
}
}

private Size getScaledImageDimensions(
int currentImageWidth,
int currentImageHeight,
int desiredImageWidth,
int desiredImageHeight)
{
/* First, we must calculate a multiplier that will be used

* to get the dimensions of the new, scaled image.
*/

double scaleImageMultiplier = 0;

/* This multiplier is defined as the ratio of the

* Desired Dimension to the Current Dimension.
* Specifically which dimension is used depends on the larger
* dimension of the image, as this will be the constraining dimension
* when we fit to the window.
*/

/* Determine if Image is Portrait or Landscape. */
if (currentImageHeight > currentImageWidth)    /* Image is Portrait */
{
/* Calculate the multiplier based on the heights. */
if (desiredImageHeight > desiredImageWidth)
{
scaleImageMultiplier = (double)desiredImageWidth / (double)currentImageWidth;
}

else
{
scaleImageMultiplier = (double)desiredImageHeight / (double)currentImageHeight;
}
}

else /* Image is Landscape */
{
/* Calculate the multiplier based on the widths. */
if (desiredImageHeight >= desiredImageWidth)
{
scaleImageMultiplier = (double)desiredImageWidth / (double)currentImageWidth;
}

else
{
scaleImageMultiplier = (double)desiredImageHeight / (double)currentImageHeight;
}
}

/* Generate and return the new scaled dimensions.

* Essentially, we multiply each dimension of the original image
* by the multiplier calculated above to yield the dimensions
* of the scaled image. The scaled image can be larger or smaller
* than the original.
*/

return new Size(
(int)(currentImageWidth * scaleImageMultiplier),
(int)(currentImageHeight * scaleImageMultiplier));
}

}

Written by Sandip

September 17, 2009 at 11:27 am

Posted in .Net, Programming

Tagged with ,