Enviar Email y Adjuntos Usando CSharp

Send Email Messages and Attachments Using C#

ByScott LysleAugust 05, 2008This article describes an approachto sending email messages with or without attachments. The coderequired to send the message is contained within a reusable class.In addition to sending messages and messages with attachments, theclass also validates the recipient email addresses using regularexpression validation.

Author Rank:Total page views :125702

Total downloads :4056

Print

Post a comment

Similar Articles

Share

Email to a friend

Bookmark

Author’s other articles

Download Files:EmailAttachments_CS.zip

Sponsored byBecome a SponsorSimilar ArticlesMost ReadTopRatedLatestIntroduction to Dynamic Data Web Application Model: PartIIIClient side validation using Validation ApplicationblocksWorking with ASP.NET Validation controlsSelective Validationin ASP.Net 2.0Validation Controls within GridView control inASP.NET 2.0More…

IntroductionThis article describes an approach to sending emailmessages with or without attachments. The code required to send themessage is contained within a reusable class. In addition tosending messages and messages with attachments, the class alsovalidates the recipient email addresses using regular expressionvalidation.

Figure 1: Test Application Main Form

SMTP ConfigurationSetting up IISYour local IIS instance has tobe properly configured in order to successfully send an emailmessage through its SMTP mail server. Even if you install IIS, theSMTP mail server installation is optional and must be explicitlyadded to the installation. If you are not sure whether or not theSMTP mail server is installed, open up the IIS control panel andcheck for the installation; if it is installed you will see areference to the Default SMTP Virtual Server in the tree view(Figure 2):

Figure 2: Default SMTP Virtual Server Installed

If the server is not installed, you will need to use the «Addand Remove Windows Components» function in the «Add and RemovePrograms» control panel to add the SMTP server to your IISinstallation. If you need to do this additional installation, onceyou’ve opened the «Add and Remove Windows Components», click on»Internet Information Services (IIS)» to highlight it and thenclick on the «Details» button (Figure 3). This will open an IISdialog; examine this dialog to locate «SMTP Service» and click onit to place a check mark on the box (Figure 4). Once this item hasbeen checked, click on the «OK» button to install the SMTPserver.

Figure 3: Windows Components Wizard

Figure 4: Adding the SMTP Service to IIS

Once the default SMTP server has been installed or verified; youcan now configure it to send email. In order to configure the SMTPserver, open the IIS control panel, locate the default SMTP servericon in the treeview, and select and right click the icon. Once thecontext menu has been displayed, locate «Properties» and click onit to open the properties menu.

Once the Default SMTP Virtual Server Properties dialog isdisplayed click on the «Access» tab (Figure 5):

Figure 5: SMTP Property Dialog

Select the «Authentication» button to display the authenticationoptions (Figure 6):

Figure 6: Authentication Options

Make sure that the Anonymous access option is checked and thatall other options are unchecked; in some instances you may wish touse the other options but in most cases involving a public websitethis is the option you’d want. Once you have verified this setting,click «OK» to close this dialog.

Back to the «Access» tab, locate and click on the «Relay» buttonto display the relay options. Note that the radio button for «Onlythe list below» is selected, and that the local host IP address hasbeen added to the list of computers permitted to relay through theSMTP server. Naturally this is OK for a development machine but indeployment, you would use the actual IP address of the web server.If no IP addresses are shown in the list, click on the «Add» buttonand add the IP address. Once finished, click on the «OK» button toaccept the changes and to dismiss the dialog. (Figure 7)

Figure 7: Relay Restrictions Dialog

Next, select the «Delivery» tab from the SMTP Server propertiesdialog (Figure 8):

Figure 8: Delivery Options Dialog

From this dialog, select the «Advanced» button to reveal theadvanced options dialog (Figure 10):

Figure 9: Advanced Delivery Dialog

From this dialog there are two points to make; first, the «Fullyqualified domain name» property should be pre-populated; you mayclick on the «Check DNS» button to validate the setting. The nextoption is probably the most critical item for the whole shootingmatch; the Smart Host property has to be set to point to a validSMTP mail server that will permit you to relay mail. For mostcases, you will key in the name of your internet provider’s defaultSMTP mail server; the address is likely to be in the format of»mail.something.com» where «something» is the internet provider’sdomain name. There are two easy ways to get this, one is, if youare using Outlook, open up Outlook and pull up the information onyour email account; the mail server will be listed there. Thesecond option is to guess and you can qualify your guess by pingingthe server.

If your internet provider’s name is «foxtrox», try pingingmail.foxtrot.com; if you get a response there, that is probably theone to use. If that does not work, contact your administrator andask them for the information on the SMTP mail server; don’t try toplug in an Exchange server, there will likely be an SMTP mailserver out there even if your company is using an Exchange server.The only other hurdle is to make sure that the SMTP mail serverwill allow you to relay and again, you may need to talk to theadministrator if the server bounces your mail. Once these settingsare made, click on the «OK» button to save the settings and closethe dialog.

The last thing to do is to check the security tab to make surethe accounts are properly configured; once done your securitysettings should look something like this (Figure 10):

Figure 10: Security Settings for the SMTP Server

Once everything is setup, click on the «OK» button to save thesettings and to close the Default SMTP Virtual Server Propertiesdialog.

Getting Started:In order to get started, unzip the includedproject and open the solution in the Visual Studio 2008environment. In the solution explorer, you should note these files(Figure 11):

Figure 11: Solution Explorer

The solution contains two projects; the EmailHandler project isa class library; it contains a class entitled, «Emailer.cs» whichcontains all of the code necessary to send email messages with andwithout attachments, and to validate email addresses. The secondproject is entitled, «EmailTestApp»; this is a win formsapplication which provides an interface that may be used toconstruct and send email messages using the Emailer classfunctions.

Code: Emailer.csThe Emailer class is used to send email messageswith or without attachments, and it contains the code used tovalidate the format of the email addresses used to define the emailsender and recipient.

The class begins with the default and added imports; note theaddition of System.Net.Mail, System.Net.Mime, andSystem.Text.RegularExpressions.

usingSystem;usingSystem.Data;usingSystem.Configuration;usingSystem.Collections;usingSystem.Linq;usingSystem.Net.Mail;usingSystem.Net.Mime;usingSystem.Text.RegularExpressions;usingSystem.Web;Thenext section contains the namespace and class declarations.

namespaceEmailHandler{publicclassEmailer{The first methodcontained in this class is used to send an email message without anattachment. The method collects the recipient email address, thesender’s email address, the email subject line, and the messagebody as arguments. Within the code, the recipient’s email addressis validated, a new mail message is constructed using the passed inarguments, an instance of an SMTP client is created using the mailserver (stored in the properties), a Boolean is set to enable therequests to include the default credentials, and then the messageis sent. If the action succeeds, the method will return a stringindicating that the submittal was successful, else, the exceptionmessage will be returned to the caller.

//////Transmit an email message to a recipient without///anyattachments//////Recipient Email Address///Sender EmailAddress///Subject Line Describing Message///The Email MessageBody///Status Message asStringpublicstaticstringSendMessage(stringsendTo,stringsendFrom,stringsendSubject,stringsendMessage){try{//validate the email addressboolbTest =ValidateEmailAddress(sendTo);// if the email address is bad, returnmessageif(bTest ==false)return»Invalid recipient email address: «+sendTo;// create the email messageMailMessagemessage=newMailMessage(sendFrom,sendTo,sendSubject,sendMessage);// createsmtp client at mail server locationSmtpClientclient=newSmtpClient(Properties.Settings.Default.SMTPAddress);// addcredentialsclient.UseDefaultCredentials =true;// sendmessageclient.Send(message);return»Message sent to «+ sendTo +» at»+DateTime.Now.ToString()+».»;}catch(Exceptionex){returnex.Message.ToString();}}

That next method contained in the class is used to send an emailmessage with an attachment. This method is the same as the previouswith the exception being that it also accepts an array listcontaining the paths to files to be included as attachments to themessage. The code is annotated and should be easy enough tofollow.

//////Transmit an email messagewith///attachments//////Recipient Email Address///Sender EmailAddress///Subject Line Describing Message///The Email MessageBody///A string array pointing to the locationof eachattachment///Status Message asStringpublicstaticstringSendMessageWithAttachment(stringsendTo,stringsendFrom,stringsendSubject,stringsendMessage,ArrayListattachments){try{//validate email addressboolbTest =ValidateEmailAddress(sendTo);if(bTest ==false)return»Invalidrecipient email address: «+ sendTo;// Create the basicmessageMailMessagemessage=newMailMessage(sendFrom,sendTo,sendSubject,sendMessage);// Theattachments array should point to a file location// where// theattachment resides – add the attachments to the//messageforeach(stringattachinattachments){Attachmentattached=newAttachment(attach,MediaTypeNames.Application.Octet);message.Attachments.Add(attached);}//create smtp client at mail server locationSmtpClientclient=newSmtpClient(Properties.Settings.Default.SMTPAddress);// Addcredentialsclient.UseDefaultCredentials =true;// sendmessageclient.Send(message);return»Message sent to «+ sendTo +» at»+DateTime.Now.ToString()+».»;}catch(Exceptionex){returnex.Message.ToString();}}

The last method contained in the Emailer class is used tovalidate an email address; this is accomplished by validating theaddress against a regular expression.

//////Confirm that an email address is valid///informat//////Full email address to validate///True if email addressisvalidpublicstaticboolValidateEmailAddress(stringemailAddress){try{stringTextToValidate= emailAddress;Regexexpression=newRegex(@»\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}»);// test email addresswith expressionif(expression.IsMatch(TextToValidate)){// is validemail addressreturntrue;}else{// is not valid emailaddressreturnfalse;}}catch(Exception){throw;}}}}

Code: frmTestEmailer.csThis form class is the only classcontained in the test application; it provides a simple interfacefor building an email message with attachments.

The class begins with the default imports.

usingSystem;usingSystem.Collections;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingEmailHandler;Thenext section contains the namespace and class declarations.

namespaceEmailTestApp{//////Test Application Form:///Thisapplication is used to test sending///email and email withattachments.///publicpartialclassfrmTestEmail:Form{Following theclass declaration, an ArrayList is declared; this is used tocontain the attachments added to the email message.

//////An arraylist containing///all of theattachments///ArrayListalAttachments;The next bit of code in theapplication is the default constructor.

//////Defaultconstructor///publicfrmTestEmail(){InitializeComponent();}The nextbit of code is the button click event handler used to addattachments to the email message. The code adds the file or filesselected from an open file dialog to the array list used to storethe file paths temporarily; the contents of the array list aswritten out and displayed in a text box contained on the form.

//////Add files to be attached to the emailmessage/////////privatevoidbtnAdd_Click(objectsender,EventArgse){if(openFileDialog1.ShowDialog()==DialogResult.OK){try{string[] arr =openFileDialog1.FileNames;alAttachments=newArrayList();txtAttachments.Text=string.Empty;alAttachments.AddRange(arr);foreach(stringsinalAttachments){txtAttachments.Text+= s +»;»;}}catch(Exceptionex){MessageBox.Show(ex.Message,»Error»);}}}

That next method contained in the class is used to exit theapplication. It is the button click event handler for the cancelbutton.

//////Exit theapplication/////////privatevoidbtnCancel_Click(objectsender,EventArgse){Application.Exit();}Thelast method contained in the test application form is used to sendthe email message. This is the button click event handler for thesend button. This method verifies that all of the required elementsof the message are available and then uses those form fields tosupply each of the arguments used in the SendMessage orSendMessageWithAttachments methods contained in the Emailer class.Based upon whether or not the message contains any attachments, theappropriate method is called.

//////Send an email message with or withoutattachments/////////privatevoidbtnSend_Click(objectsender,EventArgse){if(String.IsNullOrEmpty(txtSendTo.Text)){MessageBox.Show(«Missingrecipient address.»,»EmailError»);return;}if(String.IsNullOrEmpty(txtSendFrom.Text)){MessageBox.Show(«Missingsender address.»,»EmailError»);return;}if(String.IsNullOrEmpty(txtSubjectLine.Text)){MessageBox.Show(«Missingsubject line.»,»EmailError»);return;}if(String.IsNullOrEmpty(txtMessage.Text)){MessageBox.Show(«Missingmessage.»,»Email Error»);return;}string[] arr =txtAttachments.Text.Split(‘;’);alAttachments=newArrayList();for(inti = 0; i < arr.Length;i++){if(!String.IsNullOrEmpty(arr[i].ToString().Trim())){alAttachments.Add(arr[i].ToString().Trim());}}//if there are attachments, send message with//SendMessageWithAttachment call, else use the// standard SendMessagecallif(alAttachments.Count > 0){stringresult=Emailer.SendMessageWithAttachment(txtSendTo.Text,txtSendFrom.Text,txtSubjectLine.Text,txtMessage.Text,alAttachments);MessageBox.Show(result,»EmailTransmittal»);}else{stringresult=Emailer.SendMessage(txtSendTo.Text,txtSendFrom.Text,txtSubjectLine.Text, txtMessage.Text);MessageBox.Show(result,»EmailTransmittal»);}}}}

IMAPIhttp://www.microsoft.com/downloads/en/details.aspx?FamilyID=63ab51ea-99c9-45c0-980a-c556746fcf05&DisplayLang=enDisablingClose Button on Forms

ByGiri Ganji| 13 Sep 2007

How to disable the Close button on C# WinForms

See Also

Articles like this Articles by this author

INCLUDEPICTURE»http://s.codeproject.com/images/share_drop16.png» \*MERGEFORMATINET

24

ArticleBrowse CodeStatsRevisions

4.42 (32 votes)

Sponsored Links

Top of Form

Introduction

To prevent the user from closing the form during dataprocessing, it would be good if we disable the Close button on theform. Whenever it is required to show such a form with the Closebutton disabled, the first step is to look into the properties ofthe form to find the corresponding property. But I have found thatform does not have such a kind of property provided by VS.NET/C#.Hence we need to do it programmatically and this article presentshow to do it.

Background

In one of my projects, I had to implement a form with Closebutton disabled, so that the user cannot leave the form until itfinishes the data processing. From the form designer window inVS.NET 2005, it is possible to hide the Minimize box and Maximizebox. But there is no property called Close or Show close. Then Ihad some discussions with the team mates and got a couple of waysto do this. Among those alternatives, finally my idea got the nod.I thought of sharing this idea with The Code Project community andhence I have written this small article.

Using the Code

During construction and creation of theFormobject, .NET woulduse the default creation parameters available in the baseclassCreateParamsproperty. In fact,CreateParamsproperty isavailable inForms.Controlclass. In our form class (derivedfromSystem.Windows.Forms.Form), override this property and modifythe creation flags. For disabling the Close button use 0x200 tomodify theClassStylemember of theCreateParams.

Collapse

//// source code // Code Snippet private const intCP_NOCLOSE_BUTTON = 0x200;

protected override CreateParams CreateParams

{

get {

CreateParams myCp = base.CreateParams;

myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON ;

return myCp;

}

}

That’s it! We are done with the coding.

Points of Interest

The trick here is to override theCreateParamsproperty in ourForm with modified create flags. Directly copy the above piece ofcode and paste it to yourFormclass and it should work. Happycoding!!!

Bottom of Form

Using .NET to create a Windows XP ‘Fading-pages’ styleWizard

ByJohnWellsMCSD| 22 Dec 2002

Windows XP’s ‘Out-Of-Box-Experience’ during its setup andactivation, brought us a cool new style of Wizard with pages thatfade, and a clean blue interface.

See Also

Articles like this Articles by this author

INCLUDEPICTURE»http://s.codeproject.com/images/share_drop16.png» \*MERGEFORMATINET

4

ArticleBrowse CodeStatsRevisions

3.93 (26 votes)

Sponsored Links

Top of Form

Introduction

Most of us have probably seen the neat-o wizard Windows XP uses,to configure the operating system for the first time. This portionof the setup is called the ‘Out-Of-Box-Experience’. If you haven’tseen it, it looks much like the above screen shot of anapplicationIam working on. Unfortunately, I haven’t seen any programs taking onthis new style, and being that it’s so warm and fuzzy, I feel thecommunity at large should be implementing this sort of wizardinterface.

What is an OOBE style wizard?

Well, first off, I don’t own a multi-billion dollar company withthe resources to study user-acceptance of GUI design, nor do I havethe artistic merit to create my own. For this reason, I tend totake my lead in this area from a certain company, which does havethe resources to create usable interfaces. Anyways, Microsoft’sWindows XP OOBE wizard, complete with snazzy blue colors and niftyfading pages is a visual treat. I don’t know if it will make peoplemore productive, but a wizard like this could be the cherry on topof your application.

Why it’s not done

I believe the main reason this isn’t that common (the author hasonly seen Microsoft do it) is that, it requires a black belt in APIand some pretty good ninja moves to make a control (not a top-levelform) alter it’s opacity with time. There are a couple of options,you could use theWM_PRINTwindow message and get a picture of thebackground of the wizard form, you could create your own controlswhich inherit standard controls and add opacity functionality, oryou could (egad…) play a video (don’t try that one at home).

Pieces of the puzzle

Clean interface

Navigation buttons

Descriptive label for each page

Wizard-specific icon

Fading pagesMy method: A ‘Smoke-and-Mirrors’ solution

Smoke and Mirrors? We’re programmers, we do things (uh)correctly! Well, hear my solution before you gafaw me…. The listabove reads like just about any other wizard, and you can createthis wizard just like you would any other wizard. This part is upto you to implement. A couple ofPictureBoxes, someLabels, some nicelines (I used two gradient lines I created in Photoshop and justpopped them in my project, each is 3 pixels high). You may want tocreate aPanelobject for each page in your wizard, nothingspecial.

To cut to the chase, I tried a couple of methods and found thebest place to accomplish the fade is during the ‘next’ buttonlogic. You could create a routine namedShowPageor whatever. In myimplementation, this routine knows which page is desired, and whichpage is currently shown. Here’s an ordered list of the actions tobe taken, followed by some sample code.

1. Create a newFormto be our ‘Smoke’

2. Place thisFormabove our wizards’Panelarea

3. Set theForm’s size to cover thePanelwe’re fading

4. Ramp theForm’sopacityfrom 0%->100%

5. Hidethe currentPanel,Showthe new one

6. Ramp the firstForm’sopacityback down to 0%

7. Destroy the firstFormSample code

Collapse

‘API for fading

Private Declare Auto Function AnimateWindow Lib _

«user32.dll» (ByVal hWnd As Integer, _

ByVal dwTime As Integer, _

ByVal dwFlags As Integer _

) As BooleanPrivate Sub ShowPage(ByVal intPage As Integer, ByValintLastPage As Integer)

Dim frmSmoke Windows.Forms.Form = New Windows.Forms.Form()

With frmSmoke

.Location = New Point(Me.PointToScreen(New Point(0, 0)).X _

+ pnlTarget.Left, _

Me.PointToScreen(New Point(0, 0)).Y_

+ pnlTarget.Top)

.Size = pnlTarget.Size

.FormBorderStyle = Windows.Forms.FormBorderStyle.None

.BackColor = Color.FromArgb(71, 111, 214)

.Visible = False .ShowInTaskbar = False .StartPosition =Windows.Forms.FormStartPosition.Manual

End With Me.AddOwnedForm(frmSmoke)

‘This API is *not* asynchronus – It returns when the blend iscompleted

AnimateWindow(frmSmoke.Handle.ToInt32, 100,AnimateStyles.Blend)

‘m_Pages is an array of Panel objects

‘Hide the old panel

m_Pages(intLastPage).Enabled = Falsem_Pages(intLastPage).Visible = False ‘Set the current heading

lblHeading.Text = m_Pages(m_intCurrPage).Text

‘Show the new panel

m_Pages(intPage).Enabled = True m_Pages(intPage).Visible = Truem_Pages(intPage).BringToFront()

‘Focus on the correct default control for this wizard page

FocusDefaultControl(intPage)

‘We’ve done the switchero, fade out the smoke form to show thenext page

AnimateWindow(frmSmoke.Handle.ToInt32, 100, AnimateStyles.BlendOr _

AnimateStyles.Hide)

‘Clean up some resources

Me.RemoveOwnedForm(frmSmoke)

frmSmoke.Close()

frmSmoke = NothingEnd SubNotes

TheFormwe’re using as ‘smoke’ is basically sitting on top of thewizardForm, it’s setup such that we don’t see that it exists on thescreen, yet being a top-level window, we can fade it. Formulti-platform compatibility, you may want to create your ownfading functions usingForm.Opacityand aTimer. I’ve used an APIfunction that only works with Windows 2000 and above, but theactual implementation is up to you, this is just one of manymethods that could create an OOBE style wizard.

Additional Notes: It can be observed that at least one page ofthe Windows XP OOBE Wizard actually cross-fades pages, that is, twopages are semi-transparent and the same time, however, with thismethod, pages must fade into a solid color or background imagebefore fading into the next page.

Enjoy, and vote if you’ve enjoyed this (It gives me awarm-and-fuzzy feeling that you can’t buy with money).

License

This article has no explicit license attached to it but maycontain usage terms in the article text or the download filesthemselves. If in doubt please contact the author via thediscussion board below.

A list of licenses authors might use can be foundhereBottom ofForm

GripPanel

BySimmoTech| 19 Oct 2003

A WinForms Panel that shows a size grip when docked at thebottom of a form.

See Also

Articles like this Articles by this author

INCLUDEPICTURE»http://s.codeproject.com/images/share_drop16.png» \*MERGEFORMATINET

11

ArticleBrowse CodeStatsRevisions

3.57 (6 votes)

Sponsored Links

Top of Form

Introduction

This is not an earth-shattering new development but you mightfind a use for it in your toolbox.

It is simply a control derived from the standardWinformsPanelcontrol that draws a sizing grip when thepanelisdocked at the bottom of a form.

Background

This control was written to get around a bug in Winforms thatprevents controls anchored to the right and bottom of a formworking correctly in a derived form.

I simply wanted a base form withOKandCancelbuttons anchored tothe bottom right of the form but unfortunately, when a derived formwas resized in the designer, the next compile moved the buttons toincorrect positions.

This is documented in Microsoft Knowledge Base Article316560[1]but the workarounds are:-

1. Do not resize the form in the designer. (Which is notconvenient!)

2. Change the modifier fromprivatetoprotected. (Which mycontrols already were, so this is incorrect)

My solution to this problem was to add apanel, all docked to thebottom of the form, with the required buttons (and some emptylabels to provide spacing) docked to the right within that panel.This worked fine but it means that the form sizing grip was nolonger visible.

So I decided to write a derivedPanelthat would have a sizinggrip! What should have been a simple 5-minute job left me burningthe midnight oil determined to find out how to do this.

How it works

I used Lutz Roeder’s excellent Reflector for .NET[2]to lookintoSystem.Windows.Forms.Dllto see how Microsoft did it for a formand I also found an article by Karl E. Peterson called «Get a GripWith SubClassing»[3]written for VB which does a similar thing.

The first part, drawing the size grip itself iseasy.ControlPaint.DrawSizeGrip(part of WinForms) will draw a sizegrip of any size onto aGraphicsobject such as that provided inthePaintEventArgsparameter theOnPaintmethod.

The next bit was to make the cursor change shape and actuallyresize the form when the mouse pointer is over the size grip. To dothis, I had to override theWndProcmethod and lookforWM_NCHITTESTmessage. When this message is received, I checkwhether the mouse pointer is within the size grip and if so,basically lie to Windows and tell it that the mouse pointer is inthe lower-right corner of a border of a resizable window. At thispoint, Windows takes over and does all that is necessary!

Finally, when the window is being resized, I need to invalidatethe rectangle containing the size grip so that it will be redrawnand not leave ‘bits’ behind. At first, I Invalidated just therectangle containing the grip but when the form was resizedquickly, some bits were still left behind. Using Reflector again, Ifound that Microsoft took the easy option and Invalidated the wholecontrol so I did the same!

Oh, and I also added a dividing line at the top of the panelusingControlPaintinOnPaintagain. This is optional.

References

1. Microsoft website2. http://www.aisto.com/roeder/dotnet/3.http://archive.devx.com/premier/mgznarch/vbpj/1999/06jun99/ap0699.pdfSourcecode

Here is the source code in full:

Collapse

using System;

using System.Drawing;

using System.Runtime.InteropServices;

using System.Windows.Forms;

namespace SimmoTech.Forms {

/// /// This control works exactly the same as a normal

/// panel but, if the panel is docked at the bottom of theform,

/// then a sizing grip is added and a horizontal 3D line

/// is added at the top of panel.

/// public class GripPanel: Panel {

private const int HTBOTTOMRIGHT = 17;

private const int WM_NCHITTEST = 0x84;

private const int WM_SIZE = 0x05;

/// /// Catch some windows messages

/// /// protected override void WndProc(ref Message m) {

// Only catch messages if the panel is docked to the bottom

if (Dock == DockStyle.Bottom) {

switch (m.Msg) {

// If the panel is being resized then we

// need to redraw its contents

case WM_SIZE:

Invalidate();

break;

// If the system is asking where the mouse pointer is,

// we need to check whether it is over our sizing grip

case WM_NCHITTEST:

// Convert to client co-ordinates of parent

Point p = FindForm().PointToClient(new Point((int)m.LParam));

int x = p.X;

int y = p.Y;

Rectangle rect = Bounds;

// Is the mouse pointer over our sizing group?

// (Use 12 pixels rather than 16 otherwise

// too large an area is checked)

if (x >= rect.X + rect.Width – 12 &&

x = rect.Y + rect.Height – 12 &&

y

Publicaciones Similares