아래는 기본화면입니다.

image

이메일 형식으로 올바르게 입력했을때 전송버튼을 누르면

image

아래와 같은 메세지가 뜬다

실패할경우

image

아래와 같이 아이콘이 보이면서 자동으로 전송버튼 이벤트도 발생하지 않는다

에러검사

에러메세지 발생시키는 방법

this.errorProvider1.SetError(textBox1, errorMsg);

image

errorProvider를 끌어와서 추가한다

 

텍스트 박스에  아래와 같이 이벤트를 추가한다

image

아래의 코드를 참조해서 응용해서 코드를 처리

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestWindowsFormsApplication
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void textBox1_Validating(object sender,
                        System.ComponentModel.CancelEventArgs e)
        {
            string errorMsg;
            if (!ValidEmailAddress(textBox1.Text, out errorMsg))
            {
                // Cancel the event and select the text to be corrected by the user.
                e.Cancel = true;
                textBox1.Select(0, textBox1.Text.Length);

                // Set the ErrorProvider error with the text to display. 
                this.errorProvider1.SetError(textBox1, errorMsg);
            }
        }

        private void textBox1_Validated(object sender, System.EventArgs e)
        {
            // If all conditions have been met, clear the ErrorProvider of errors.
            errorProvider1.SetError(textBox1, "");
        }
        public bool ValidEmailAddress(string emailAddress, out string errorMessage)
        {
            // Confirm that the e-mail address string is not empty.
            if (emailAddress.Length == 0)
            {
                errorMessage = "e-mail address is required.";
                return false;
            }

            // Confirm that there is an "@" and a "." in the e-mail address, and in the correct order.
            if (emailAddress.IndexOf("@") > -1)
            {
                if (emailAddress.IndexOf(".", emailAddress.IndexOf("@")) > emailAddress.IndexOf("@"))
                {
                    errorMessage = "";
                    return true;
                }
            }

            errorMessage = "e-mail address must be valid e-mail address format.\n" +
               "For example 'someone@example.com' ";
            return false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("전송완료!");
        }

    }
}

에러발생을 하고 싶지 않다면?

image

 

좀 친절하게 메세지를 표시!

image

위의 간단한 설정으로 마우스가 올라가면 메세지가 표시된다

image

private void button1_Click(object sender, System.EventArgs e)
{
    Stream myStream = null;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "c:\\" ;
    openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
    openFileDialog1.FilterIndex = 2 ;
    openFileDialog1.RestoreDirectory = true ;

    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        try
        {
            if ((myStream = openFileDialog1.OpenFile()) != null)
            {
                using (myStream)
                {
                    // Insert code to read the stream here.
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
        }
    }
}

 

사용자정의 DataGridView Cell 만들기!

출처 http://msdn.microsoft.com/ko-kr/library/7tas5c80(VS.80).aspx

using System;
using System.Windows.Forms;

public class CalendarColumn : DataGridViewColumn
{
    public CalendarColumn() : base(new CalendarCell())
    {
    }

    public override DataGridViewCell CellTemplate
    {
        get
        {
            return base.CellTemplate;
        }
        set
        {
            // Ensure that the cell used for the template is a CalendarCell.
            if (value != null && 
                !value.GetType().IsAssignableFrom(typeof(CalendarCell)))
            {
                throw new InvalidCastException("Must be a CalendarCell");
            }
            base.CellTemplate = value;
        }
    }
}

public class CalendarCell : DataGridViewTextBoxCell
{

    public CalendarCell()
        : base()
    {
        // Use the short date format.
        this.Style.Format = "d";
    }

    public override void InitializeEditingControl(int rowIndex, object 
        initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
    {
        // Set the value of the editing control to the current cell value.
        base.InitializeEditingControl(rowIndex, initialFormattedValue, 
            dataGridViewCellStyle);
        CalendarEditingControl ctl = 
            DataGridView.EditingControl as CalendarEditingControl;
        ctl.Value = (DateTime)this.Value;
    }

    public override Type EditType
    {
        get
        {
            // Return the type of the editing contol that CalendarCell uses.
            return typeof(CalendarEditingControl);
        }
    }

    public override Type ValueType
    {
        get
        {
            // Return the type of the value that CalendarCell contains.
            return typeof(DateTime);
        }
    }

    public override object DefaultNewRowValue
    {
        get
        {
            // Use the current date and time as the default value.
            return DateTime.Now;
        }
    }
}

class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl
{
    DataGridView dataGridView;
    private bool valueChanged = false;
    int rowIndex;

    public CalendarEditingControl()
    {
        this.Format = DateTimePickerFormat.Short;
    }

    // Implements the IDataGridViewEditingControl.EditingControlFormattedValue 
    // property.
    public object EditingControlFormattedValue
    {
        get
        {
            return this.Value.ToShortDateString();
        }
        set
        {
            String newValue = value as String;
            if (newValue != null)
            {
                this.Value = DateTime.Parse(newValue);
            }
        }
    }

    // Implements the 
    // IDataGridViewEditingControl.GetEditingControlFormattedValue method.
    public object GetEditingControlFormattedValue(
        DataGridViewDataErrorContexts context)
    {
        return EditingControlFormattedValue;
    }

    // Implements the 
    // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
    public void ApplyCellStyleToEditingControl(
        DataGridViewCellStyle dataGridViewCellStyle)
    {
        this.Font = dataGridViewCellStyle.Font;
        this.CalendarForeColor = dataGridViewCellStyle.ForeColor;
        this.CalendarMonthBackground = dataGridViewCellStyle.BackColor;
    }

    // Implements the IDataGridViewEditingControl.EditingControlRowIndex 
    // property.
    public int EditingControlRowIndex
    {
        get
        {
            return rowIndex;
        }
        set
        {
            rowIndex = value;
        }
    }

    // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
    // method.
    public bool EditingControlWantsInputKey(
        Keys key, bool dataGridViewWantsInputKey)
    {
        // Let the DateTimePicker handle the keys listed.
        switch (key & Keys.KeyCode)
        {
            case Keys.Left:
            case Keys.Up:
            case Keys.Down:
            case Keys.Right:
            case Keys.Home:
            case Keys.End:
            case Keys.PageDown:
            case Keys.PageUp:
                return true;
            default:
                return false;
        }
    }

    // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit 
    // method.
    public void PrepareEditingControlForEdit(bool selectAll)
    {
        // No preparation needs to be done.
    }

    // Implements the IDataGridViewEditingControl
    // .RepositionEditingControlOnValueChange property.
    public bool RepositionEditingControlOnValueChange
    {
        get
        {
            return false;
        }
    }

    // Implements the IDataGridViewEditingControl
    // .EditingControlDataGridView property.
    public DataGridView EditingControlDataGridView
    {
        get
        {
            return dataGridView;
        }
        set
        {
            dataGridView = value;
        }
    }

    // Implements the IDataGridViewEditingControl
    // .EditingControlValueChanged property.
    public bool EditingControlValueChanged
    {
        get
        {
            return valueChanged;
        }
        set
        {
            valueChanged = value;
        }
    }

    // Implements the IDataGridViewEditingControl
    // .EditingPanelCursor property.
    public Cursor EditingPanelCursor
    {
        get
        {
            return base.Cursor;
        }
    }

    protected override void OnValueChanged(EventArgs eventargs)
    {
        // Notify the DataGridView that the contents of the cell
        // have changed.
        valueChanged = true;
        this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
        base.OnValueChanged(eventargs);
    }
}

public class Form1 : Form
{
    private DataGridView dataGridView1 = new DataGridView();

    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new Form1());
    }

    public Form1()
    {
        this.dataGridView1.Dock = DockStyle.Fill;
        this.Controls.Add(this.dataGridView1);
        this.Load += new EventHandler(Form1_Load);
        this.Text = "DataGridView calendar column demo";
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        CalendarColumn col = new CalendarColumn();
        this.dataGridView1.Columns.Add(col);
        this.dataGridView1.RowCount = 5;
        foreach (DataGridViewRow row in this.dataGridView1.Rows)
        {
            row.Cells[0].Value = DateTime.Now;
        }
    }
}

예제

 

아래는 TestClass  에 IDataContextState 라는 인터페이스가 구현되어져 있을떄 입니다.

인터페이스

이 인터페이스는 클라이언트 측에서 데이터가 삭제/수정/신규 상태를 관리하게 위해서 만들었습니다. 이인터페이스를 구현해놓은 클래스는

    //특정 클래스에서 이 인터페이스를 구현해 놓으면 추가/수정/삭제를 알수있습니다.
	public interface IDataContextState
    {
        bool IsNew { set; get; }
        bool IsDeleted { get; set; }
        bool IsEdited { get; set; }
    }

IDataContextState 상태 변경시키키 호출

그리듀 뷰 에서 삭제를 눌렀을때 발생하는 이벤트

        private void dgvDocCategory_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            Contract.Data.Doc.DocCategory df = e.Row.DataBoundItem as Contract.Data.Doc.DocCategory;
			//RepositoryManager<T> : List<T>  형태입니다. 여기에 Delete 메소를 추가하였습니다.
            DocCategoryRepositoryManager.Delete(df);
                
        }

특정 클래스에 인터페이스가 구현 되어져 있는지 체크하기하고 상태변경

    public class RepositoryManager<T> : List<T> 
    {

        public void Delete<T>(T t) {          
            Type type = t.GetType().GetInterface("IDataContextState"); 
            if( type != null ) //IDataContextState 가 구현되어져있음 삭제 형태를 변경합니다.
            {
                ((Contract.Data.IDataContextState)t).IsDeleted = true;
            }
        }
    }

image

image

컨트롤 값이 잘못되었을 때 오류 아이콘을 표시하려면?

 

protected void textBox1_Validating (object sender,
   System.ComponentModel.CancelEventArgs e)
{
   try
   {
      int x = Int32.Parse(textBox1.Text);
      errorProvider1.SetError(textBox1, "");
   }
   catch (Exception e)
   {
      errorProvider1.SetError(textBox1, "Not an integer value.");
   }
}
        private void Form1_Load(object sender, EventArgs e)
        {
            string fmt = "0000000000";
            double intValue = 2010;

            string s = intValue.ToString(fmt);
            //출력은 0000002010
            this.label1.Text =s;
     
            
        }

끝~

 

아래는 참고하세요

특정 길이까지 숫자 값 앞에 0을 채우려면

string fmt = "00000000.##";   
int intValue = 1053240;   
decimal decValue = 103932.52m;   
float sngValue = 1549230.10873992f;   
double dblValue = 9034521202.93217412;   

outputBlock.FontFamily = new System.Windows.Media.FontFamily("Courier New");   

// Display the numbers using the ToString method. 
outputBlock.Text += intValue.ToString(fmt) + "\n";   
outputBlock.Text += decValue.ToString(fmt) + "\n";   
outputBlock.Text += sngValue.ToString(fmt) + "\n";   
outputBlock.Text += sngValue.ToString(fmt) + "\n";   
outputBlock.Text += "\n";   

// Display the numbers using composite formatting. 
string formatString = " {0,15:" + fmt + "}\n";   
outputBlock.Text += String.Format(formatString, intValue);   
outputBlock.Text += String.Format(formatString, decValue);   
outputBlock.Text += String.Format(formatString, sngValue);   
outputBlock.Text += String.Format(formatString, dblValue);   
// The example displays the following output: 
//       01053240 
//       00103932.52 
//       01549230 
//       01549230 
//        
//               01053240 
//            00103932.52 
//               01549230 
//          9034521202.93    

 

특정 길이까지 정수 앞에 0을 채우려면?

byte byteValue = 254;
short shortValue = 10342;
int intValue = 1023983;
long lngValue = 6985321;
ulong ulngValue = UInt64.MaxValue;

outputBlock.FontFamily = new System.Windows.Media.FontFamily("Courier New");

// Display integer values by caling the ToString method.
outputBlock.Text += String.Format("{0,22} {1,22}", byteValue.ToString("D8"), byteValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", shortValue.ToString("D8"), shortValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", intValue.ToString("D8"), intValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", lngValue.ToString("D8"), lngValue.ToString("X8")) + "\n";
outputBlock.Text += String.Format("{0,22} {1,22}", ulngValue.ToString("D8"), ulngValue.ToString("X8")) + "\n";
outputBlock.Text += "\n";

// Display the same integer values by using composite formatting.
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", byteValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", shortValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", intValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", lngValue) + "\n";
outputBlock.Text += String.Format("{0,22:D8} {0,22:X8}", ulngValue) + "\n";
// The example displays the following output:
//                     00000254               000000FE
//                     00010342               00002866
//                     01023983               000F9FEF
//                     06985321               006A9669
//         18446744073709551615       FFFFFFFFFFFFFFFF
//       
//                     00000254               000000FE
//                     00010342               00002866
//                     01023983               000F9FEF
//                     06985321               006A9669
//         18446744073709551615       FFFFFFFFFFFFFFFF
//         18446744073709551615       FFFFFFFFFFFFFFFF

 

정수 앞에 특정 개수의 0을 채우려면?

  • 정수 값에서 표시할 선행 0의 개수를 결정합니다.

  • 정수를 10진수 값으로 표시할지 또는 16진수 값으로 표시할지를 결정합니다.10진수 값으로 형식을 지정하려면 "D" 표준 형식 지정자를 사용해야 합니다. 16진수 값으로 형식을 지정하려면 "X" 표준 형식 지정자를 사용해야 합니다.

  • 정수 값의 ToString("D").Length 또는 ToString("X").Length 메서드를 호출하여 0이 채워지지 않은 숫자 문자열의 길이를 확인합니다.

  • 형식이 지정된 문자열에 포함하려는 선행 0의 개수를 0이 채워지지 않은 숫자 문자열의 길이에 더합니다.이 값은 0이 채워진 문자열의 총 길이를 정의합니다.

  • 정수 값의 ToString(String) 메서드를 호출하고 문자열 "Dn"(10진수 문자열의 경우) 및 "Xn"(16진수 문자열의 경우)을 전달합니다. 여기서 n은 0이 채워진 문자열의 총 길이를 나타냅니다.복합 형식 지정을 지원하는 메서드에 "Dn" 또는 "Xn" 형식 문자열을 사용할 수도 있습니다.

  • int value = 160934;
    int decimalLength = value.ToString("D").Length + 5;
    int hexLength = value.ToString("X").Length + 5; 
    
    outputBlock.FontFamily = new System.Windows.Media.FontFamily("Courier New"); 
    
    outputBlock.Text += value.ToString("D" + decimalLength.ToString()) + "\n";
    outputBlock.Text += value.ToString("X" + hexLength.ToString()) + "\n";
    // The example displays the following output:
    //       00000160934
    //       00000274A6      
    

    행에 바인딩된 개체에 액세스(BindingList 사용권장)

    BindList은 목록 데이터 원본이 편집을 지원하도록 하기 위해 데이터 바인딩 인프라에 필요한 최소 인터페이스구현되어져 있따!

    http://msdn.microsoft.com/ko-kr/library/ms132679.aspx

     

    void invoiceButton_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
        {
            Customer cust = row.DataBoundItem as Customer;
            if (cust != null)
            {
                cust.SendInvoice();
            }
        }
    }

     

    표시를 위해 셀 내용의 서식을 지정해야 하는 경우?

    CellFormatting 이벤트

    private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        // If the column is the Artist column, check the
        // value.
        if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Artist")
        {
            if (e.Value != null)
            {
                // Check for the string "pink" in the cell.
                string stringValue = (string)e.Value;
                stringValue = stringValue.ToLower();
                if ((stringValue.IndexOf("pink") > -1))
                {
                    e.CellStyle.BackColor = Color.Pink;
                }
    
            }
        }
        else if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Release Date")
        {
            ShortFormDateFormat(e);
        }
    }
    
    //Even though the date internaly stores the year as YYYY, using formatting, the
    //UI can have the format in YY.  
    private static void ShortFormDateFormat(DataGridViewCellFormattingEventArgs formatting)
    {
        if (formatting.Value != null)
        {
            try
            {
                System.Text.StringBuilder dateString = new System.Text.StringBuilder();
                DateTime theDate = DateTime.Parse(formatting.Value.ToString());
    
                dateString.Append(theDate.Month);
                dateString.Append("/");
                dateString.Append(theDate.Day);
                dateString.Append("/");
                dateString.Append(theDate.Year.ToString().Substring(2));
                formatting.Value = dateString.ToString();
                formatting.FormattingApplied = true;
            }
            catch (FormatException)
            {
                // Set to false in case there are other handlers interested trying to
                // format this DataGridViewCellFormattingEventArgs instance.
                formatting.FormattingApplied = false;
            }
        }
    }

    http://msdn.microsoft.com/ko-kr/library/ms404353.aspx

    Windows Forms DataGridViewComboBoxCell

    드롭다운 목록의 개체 액세스

    만들기

            public Form1()
            {
                InitializeComponent();
    
    
                employees.Add(new Employee("Harry"));
                employees.Add(new Employee("Sally"));
                employees.Add(new Employee("Roy"));
                employees.Add(new Employee("Pris"));
    
                DataSet1TableAdapters.SchoolTableAdapter adapter = new TestWindowsFormsApplication.DataSet1TableAdapters.SchoolTableAdapter();
                DataSet1.SchoolDataTable dt = adapter.GetData();
                this.bindingSource1.DataSource = employees;
    
    
    
                ////ComboBoxColumn 생성
                DataGridViewComboBoxColumn assignedtocolumn = new DataGridViewComboBoxColumn();
                assignedtocolumn.Name = "Column1";
                assignedtocolumn.DisplayMember = "name";
                assignedtocolumn.ValueMember = "self";
                assignedtocolumn.DataSource = employees;
                
                this.dataGridView1.AutoGenerateColumns = false;
                dataGridView1.Columns.Add(assignedtocolumn);
                this.dataGridView1.DataSource = dt;
               
            }

    클릭했을때 값 가져오기

       private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
            {
    
    
                // Retrieve the Employee object from the "Assigned To" cell.
                Employee assignedTo = dataGridView1.Rows[e.RowIndex].Cells["Column1"].Value as Employee;
                // Retrieve the task ID.
                string taskID = dataGridView1[0, e.RowIndex].Value.ToString();
    
                // Request status through the Employee object if present. 
                if (assignedTo != null)
                {
                    assignedTo.RequestStatus(taskID);
                }
                else
                {
                    MessageBox.Show(String.Format(
                        "Task {0} is unassigned.", taskID), "Status Request");
                }
    
            }

     

     

     

    선택된 드롭다운리스트 개체가져오기

    CellClick 이벤트등록

    // Add a CellClick handler to handle clicks in the button column. 
    dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);

    이벤트가 일어났을때 처리

    // Retrieve the Employee object from the "Assigned To" cell.
    Employee assignedTo = dataGridView1.Rows[e.RowIndex].Cells["Assigned To"].Value as Employee;

    DataGridViewLinkCell 등등 기본컨트롤 값 가져오기

            private void dgvDocWork_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
            {
                DataGridViewLinkCell linkCell =dgvDocWork.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewLinkCell;
    
            }
    
            private void dgvDocWork_CellContentClick(object sender, DataGridViewCellEventArgs e)
            {
    
            }
    

    컨트롤에서 새 행에 기본값 지정

    (새행추가시 미리 입력값을 넣어주기)

    private void dataGridView1_DefaultValuesNeeded(object sender,
        System.Windows.Forms.DataGridViewRowEventArgs e)
    {
        e.Row.Cells["Region"].Value = "WA";
        e.Row.Cells["City"].Value = "Redmond";
        e.Row.Cells["PostalCode"].Value = "98052-6399";
        e.Row.Cells["Region"].Value = "NA";
        e.Row.Cells["Country"].Value = "USA";
        e.Row.Cells["CustomerID"].Value = NewCustomerId();
    }

    유효성검사

    private void dataGridView1_CellValidating(object sender,
        DataGridViewCellValidatingEventArgs e)
    {
        // Validate the CompanyName entry by disallowing empty strings.
        if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
        {
            if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
            {
                dataGridView1.Rows[e.RowIndex].ErrorText =
                    "Company Name must not be empty";
                e.Cancel = true;
            }
        }
    }
    
    void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        // Clear the row error in case the user presses ESC.   
        dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty;
    }

    데이터 입력 중에 발생하는 오류 처리

    DataGridViewDataError 이벤트를 처리

    private void dataGridView1_DataError(object sender,
        DataGridViewDataErrorEventArgs e)
    {
        // If the data source raises an exception when a cell value is 
        // commited, display an error message.
        if (e.Exception != null &&
            e.Context == DataGridViewDataErrorContexts.Commit)
        {
            MessageBox.Show("CustomerID value must be unique.");
        }
    }

    런타임에 리소스 액세스

    런타임에 리소스에 액세스하려면 다른 클래스 멤버의 경우와 마찬가지로 해당 리소스를 참조하기만 하면 됩니다. 다음 예제에서는 Image01이라는 비트맵 리소스를 검색하는 방법을 보여 줍니다. Resources 클래스는 <projectName>.Properties라는 네임스페이스에 있으므로 각 리소스에 대해 정규화된 이름을 사용하거나 Resources 클래스에 액세스할 소스 파일에 적절한 using 지시문을 추가해야 합니다.

    System.Drawing.Bitmap bitmap1 = myProject.Properties.Resources.Image01;

    내부적으로 get 속성은 ResourceManager 클래스를 사용하여 이 개체의 새 인스턴스를 만듭니다.

    리소스 검색

    System.Reflection.Assembly thisExe;
    thisExe = System.Reflection.Assembly.GetExecutingAssembly();
    System.IO.Stream file = 
        thisExe.GetManifestResourceStream("AssemblyName.ImageFile.jpg");
    this.pictureBox1.Image = Image.FromStream(file);

    ResourceManager

    현재 문화권에 대해 지정된 오브젝트 리소스의 값을 가져옵니다.

            internal static System.Drawing.Bitmap Cancel {
                get {
                    object obj = ResourceManager.GetObject("Cancel", resourceCulture);
                    return ((System.Drawing.Bitmap)(obj));
                }
            }

    .resx 리소스 파일 형식은

    XML 태그 내에 개체와 문자열을 지정하는 XML 엔트리로 구성됩니다. 메모장이나 Microsoft Word 같은 텍스트 편집기에서 .resx 파일을 열면 파일에 대한 쓰기, 구문 분석 및 조작이 가능합니다. .resx 파일을 볼 때 이 이진 정보가 리소스 매니페스트의 일부인 경우에는 포함된 개체(예: 그림)의 이진 형식을 실제로 볼 수 있습니다. 이 이진 정보와는 별도로 .resx 파일을 완벽하게 읽고 유지 관리할 수 있습니다.

     

    헤더 정보 다음에는 .txt 파일에서 문자열을 지정하는 것과 매우 유사한 이름/값 쌍 방식으로 각 엔트리를 기술합니다. .resx 형식의 이름/값 쌍은 XML 코드에 래핑되어 문자열 또는 개체 값을 기술합니다. .resx 파일에 문자열이 추가되면 다음 예제와 같이 문자열 이름은 <data> 태그에 포함하고 값은 <value> 태그로 묶습니다

    <data name="string1">
        <value>hello</value>
    </data>

     

    다음 예제에서는 .resx 파일에 저장된 Int32 개체와 실제 .gif 파일의 이진 정보를 보유하는 비트맵 개체의 시작 부분을 보여 줍니다.

    <data name="i1" type="System.Int32, mscorlib">
        <value>20</value>
    </data>

    <data name="flag" type="System.Drawing.Bitmap, System.Drawing,  
    Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    mimetype="application/x-microsoft.net.object.bytearray.base64">
        <value>
            AAEAAAD/////AQAAAAAAAAAMAgAAADtTeX…
        </value>
    </data>

     

    ResXResourceWriter 클래스 사용 리소스 저장하기

    using System;
    using System.Drawing;
    using System.Resources;
     
    public class SampleClass
    {
        public static void Main() 
        {
            Image img = Image.FromFile("en-AU.jpg");
            ResXResourceWriter rsxw = new ResXResourceWriter("en-AU.resx"); 
            rsxw.AddResource("en-AU.jpg",img);
            rsxw.Close();
        }
    }

     

    로컬 및 원격 프로세스에 대한 액세스를 제공하고 로컬 시스템 프로세스를 시작하고 중지할 수 있습니다.

    이 예제에서는 Process.Start 메서드를 사용하여 MSPaint 응용 프로그램을 로드하고 실행합니다.

    예제
    System.Diagnostics.Process.Start("mspaint.exe");

    코드 컴파일

    코드를 복사한 다음 콘솔 응용 프로그램의 Main 메서드에 붙여넣습니다.

     

    "mspaint.exe"를 실행할 응용 프로그램의 경로로 바꿉니다.

    강력한 프로그래밍

    다음의 경우에는 예외가 발생합니다.

     

    상세예제

    using System;
    using System.Diagnostics;
    using System.ComponentModel;
    
    namespace MyProcessSample
    {
    	/// <summary>
    	/// Shell for the sample.
    	/// </summary>
    	class MyProcess
    	{
    	   
    		/// <summary>
    		/// Opens the Internet Explorer application.
    		/// </summary>
    		void OpenApplication(string myFavoritesPath)
    		{
    			// Start Internet Explorer. Defaults to the home page.
    			Process.Start("IExplore.exe");
    				    
    		    // Display the contents of the favorites folder in the browser.
    		    Process.Start(myFavoritesPath);
    
    		}
    		
    		/// <summary>
    		/// Opens urls and .html documents using Internet Explorer.
    		/// </summary>
    		void OpenWithArguments()
    		{
    			// url's are not considered documents. They can only be opened
    			// by passing them as arguments.
    			Process.Start("IExplore.exe", "www.northwindtraders.com");
    			
    			// Start a Web page using a browser associated with .html and .asp files.
    			Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm");
    			Process.Start("IExplore.exe", "C:\\myPath\\myFile.asp");
    		}
    		
    		/// <summary>
    		/// Uses the ProcessStartInfo class to start new processes, both in a minimized 
    		/// mode.
    		/// </summary>
    		void OpenWithStartInfo()
    		{
    			
    			ProcessStartInfo startInfo = new ProcessStartInfo("IExplore.exe");
    			startInfo.WindowStyle = ProcessWindowStyle.Minimized;
    			
    			Process.Start(startInfo);
    			
    			startInfo.Arguments = "www.northwindtraders.com";
    			
    			Process.Start(startInfo);
    			
    		}
    
    		static void Main()
    		{
                		// Get the path that stores favorite links.
                		string myFavoritesPath = 
                    	Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
    
                		MyProcess myProcess = new MyProcess();
    
    			myProcess.OpenApplication(myFavoritesPath);
    			myProcess.OpenWithArguments();
    			myProcess.OpenWithStartInfo();
    
           		}	
    	}
    }

    image

    버튼설정을 하면 기본적인 이미지가 딸려오게 Custom Controls 을 제작

    Custom Controls을 만들면 도구상자에 등록되어 간편하게 기본컨트롤 이용하는거 처럼 이용할수 있다

    image

     

    만들기시작!

    image

     

     

    image

    화면에서

    이미지리스트를 추가해서 사용할 이미지를 등록한다

    image

     

    image

     

     

    소스

    public partial class ImageButton : System.Windows.Forms.Button 을 상속받는다

    image

    위와같이 변경해주면 속성값을 변경해줄수도 있음

    여기서 컨트롤 기본값을 설정해도 된다 ㅋ

    image

     

    설정할수 있는 속성을 하나 만든다 기본값으로 OK 주었기 때문에 컨트롤 기본이지는 OK 이미지다

    image

    image

    위와같이 설정 해놓으면 컨트롤 사용할때

    아래와 같이 사용할수 있다.

    image

    이걸로 초간단 Custom Controls 만들기 끝~

     

     

     

     [
         Browsable(true)
       
        
        ]
        public partial class ImageButton : System.Windows.Forms.Button
        {
            public enum EnumImage {OK , CANCEL , DELETE , UPDATE , MOVE }
            public ImageButton()
            {
                InitializeComponent();
                this.ImageList = this.imageListMain;
                this.TextImageRelation = TextImageRelation.ImageBeforeText;
    
    
              
                string imagekey = Enum.GetName(typeof(EnumImage), ImageType);
                this.ImageKey = imagekey;
               
                
            }
    
            protected override void OnPaint(PaintEventArgs pe)
            {
                base.OnPaint(pe);
    
               
               
            }
    
            [DefaultValue(EnumImage.OK)]
            public EnumImage ImageType
            {
                set;
                get;
            }
    
         
            
            
            
        }

     

     

    ImageList도 귀찮으면

    image

    이미지를 넣은다음에 OnPaint 이벤트에서 저렇게 해주면 끝~

            protected override void OnPaint(PaintEventArgs pe)
            {
                string imagekey = Enum.GetName(typeof(EnumImage), ImageType);
                this.Image = (Image)Properties.Resources.ResourceManager.GetObject(imagekey);
                base.OnPaint(pe);
    
    
    
               
            }

    + Recent posts