1. DLL파일 만들기(생성하기)


Visual Studio 2008에서 파일 --> 새로만들기 --> 새 프로젝트 --> 기타프로젝트 형식 --> Visual Studio 솔루션에서 "빈솔루션"에 이름과 저장위치 정하고 "프로젝트" 생성하기 --> 솔루션 탐색기의 프로젝트(여기서는 "DLL파일만들기"로 프로젝트 이름지정)에서 마우스 우클릭 --> 추가 --> 새 프로젝트 추가에서 "프로젝트 형식 --> C#" --> "Visual Studio에 설치되어 있는 템플릿"에서 "클래스 라이브러리"선택 후 이름(여기서는 "Calculator"로 클래스 라이브러리의 이름 지정)과 저장위치 정한 후 프로젝트 만들기 --> "Calculator"클래스 라이브러리의 Class1.cs 삭제 --> "Calculator"클래스 라이브러리 우클릭 --> 추가 --> 새항목 --> "클래스"로 선택하여 이름 지정후(여기서는 Plus.cs로 이름지정) 저장 --> 간단한 덧셈관련 코드 작성 --> Calculator에 마우스 우클릭하여 "빌드"하여 "Calculator.dll"이라는 DLL파일 만들기



==> Plus.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Calculator
{
    public class Plus
    {
        public static int Execute(int a, int b)
        {
            return (a + b);
        }
    }
}





2. "같은 프로젝트" 또는 "다른 프로젝트"에 있는 클래스의 코드 참조

"DLL파일만들기" 프로젝트에서 마우스 우클릭 --> 추가 --> 새 프로젝트 추가에서 "프로젝트 형식 --> C#" --> "Visual Studio에 설치되어 있는 템플릿"에서 "콘솔 응용 프로그램"선택 후 이름(여기서는 "ConCalculator"로 프로젝트 이름 지정)과 저장위치 정한 후 프로젝트 만들기 --> "ConCalculator"에 속해있는 "참조"에서 마우스 우클릭 후 "참조 추가"클릭 --> "참조 추가"창에서 "프로젝트"메뉴 탭 클릭 --> '프로젝트 이름'이 "Calculator" 선택 후 '확인버튼 클릭'하면 "Calculator"가 "ConCalculator"의 "참조"목록에 추가된다. --> "ConCalculator"의 "Program.cs"에서 "Calculator"클래스 라이브러리의 "Plus.cs"클래스의 코드를 참조한다.(다른 클래스의 참조하여 연산 또는 동작을 할 수 있다.) 




==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            int b = 5;

            Console.WriteLine("{0}", Calculator.Plus.Execute(a, b)); // 15
        }
    }
}



3. WinForm의 예제로 DLL파일 참조하기(위의 2번 예제와 실행방식이 비슷함.)

"DLL파일만들기" 프로젝트에서 마우스 우클릭 --> 추가 --> 새 프로젝트 추가에서 "프로젝트 형식 --> C#" --> "Visual Studio에 설치되어 있는 템플릿"에서 "Windows Forms 응용 프로그램"선택 후 이름(여기서는 "WinCalculator"로 프로젝트 이름 지정)과 저장위치 정한 후 프로젝트 만들기 --> "WinCalculator"에 속해있는 "참조"에서 마우스 우클릭 후 "참조 추가"클릭 --> "참조 추가"창에서 "찾아보기"메뉴 탭 클릭 --> '찾는위치'와 '파일이름'을 검색하여 위의 "1"에서 만든(생성한) "DLL파일"을 선택 후 확인 버튼을 눌러 참조시킨다.(여기서는 "1"에서 만든 "Calculator.dll"을 선택("Calculator\bin\Debug\Calculator.dll")하여 참조시킨다.) "Calculator.dll" 선택 후 '확인버튼 클릭'하면 "Calculator"가 "WinCalculator"의 "참조"목록에 추가된다. --> "Form1.cs [디자인]" 폼에 'TextBox' 2개 "Label" 1개 "Button" 1개(속성에서 "Text -> 더하기"로 변경) 추가 후 "Button" 더블클릭하여 이벤트핸들러 아래 형광펜으로 색칠된 부분으로 코드작성


==> Form1.cs [디자인]





==> Form1.cs

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            int a = Convert.ToInt32(textBox1.Text);
            int b = Convert.ToInt32(textBox2.Text);

            label1.Text =
                Convert.ToString(Calculator.Plus.Execute(a, b));
        }
    }
}



< 실행결과 >

--> 'TextBox'에 값 2개 입력후 '더하기' 버튼 누르면 'Label1'에 결과값 출력 됨.("1"에서 만든(생성한) 'Calculator'프로젝트의 "Calculator.dll"이 "WinCalculator"프로젝트에 참조된 결과임.)






4. 웹 사이트의 예제로 DLL파일 참조하기("dll"파일을 복사해서 생성한 웹 사이트(여기서는 "WebCalculator")에 내가 만든 "Bin"폴더에 "dll"파일을 붙여넣은 후 참조하는 방법.)

"DLL파일만들기" 프로젝트에서 마우스 우클릭 --> 추가 --> "새 웹 사이트" 클릭 --> '새 웹 사이트 추가' 창에서 "Visual Studio에 설치되어 있는 템플릿"에서 "ASP.NET 웹 사이트"선택 / '언어' -> 'Visual C#'으로 선택 / 저장위치 정한 후 프로젝트 만들기('= 새 웹사이트 추가', 여기서는 "WebCalculator"로 프로젝트 이름 지정) --> '솔루션 탐색기'의 "WebCalculator" 마우스 우클릭 --> "ASP.NET 폴더 추가" --> "Bin"클릭하여 "Bin"이름의 폴더 만들기 --> "Calculator\bin\Debug\Calculator.dll" 경로로 들어가서 "1"번째에서 만든 "Calculator.dll"파일을 복사 --> "WebCalculator\Bin(여기서의 Bin폴더는 "ASP.NET 폴더 추가" --> "Bin"클릭하여 내가 생성한 폴더임.)"의 경로로 들어가서 복사했던 "Calculator.dll"파일을 붙여넣기 --> "WebCalculator"아래 있는 "Default.aspx" 더블클릭 -->"Default.aspx"페이지의 왼쪽 아래쪽에 "디자인"버튼 클릭 --> 도구상자에서 'TextBox' 2개 "Label" 1개 "Button" 1개(속성에서 "Text -> 더하기"로 변경) 추가("Default.aspx"의 '디자인'에서 만든 폼형식은 아래와 같다.) -->


 


--> "Button" 더블클릭하여 "Default.aspx.cs"(Default.aspx에 속해있음.)에 생성되는 이벤트핸들러코드에 아래 형광펜으로 색칠된 부분으로 코드작성 --> "Default.aspx"에서 마우스 우클릭 --> "브라우저에서 보기"클릭





==> Default.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        int a = Convert.ToInt32(TextBox1.Text);
        int b = Convert.ToInt32(TextBox2.Text);

        Label1.Text = Convert.ToString(Calculator.Plus.Execute(a, b));
    }

}




< 실행결과 >

--> "1"에서 생성한 "Calculator.dll"파일을 "Calculator\bin\Debug"의 경로로 들어가서 복사 후 "WebCalculator\Bin"의 경로로 가서(여기 "Bin"폴더는 내가 생성한 폴더임.) 붙여넣기 하여 "Calculator.dll"파일을 "Bin"폴더에 추가하였다. 그 결과 "브라우저에서 보기"를 실행하면 '웹 사이트'에서 "Calculator.dll"파일을 이용하여 실행되는 것을 볼 수 있다. 








Posted by holland14
:


* '도구상자 - 인쇄'에서 "PrintPreviewDialog"를 폼에 드래그&드롭



==> Program.cs



using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace DotNetNote
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new DotNetNote());
        }
    }
}




==============================================================================================




==> DotNetNote.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;

namespace DotNetNote
{
    public partial class DotNetNote : Form
    {
        #region Constructors
        public DotNetNote()
        {
            InitializeComponent();
        }
        #endregion

        #region Private Member Variables
        private bool _IsTextChanged; // 텍스트 변경 여부
        #endregion

        #region Private Methods
        /// <summary>
        /// 파일을 저장할지 결정 메서드
        /// </summary>
        private void SaveText()
        {
            if (this.Text == "제목 없음 - 메모장")
            {
                DialogResult objDr = sfdDotNetNote.ShowDialog();
                if (objDr != DialogResult.Cancel)
                {
                    string strFileName = sfdDotNetNote.FileName;
                    SaveFile(strFileName);
                }
            }
            else
            {
                string strFileName = this.Text; // 파일 전체 이름
                SaveFile(strFileName);
            }
        }

        /// <summary>
        /// 실제 파일을 저장하는 메서드
        /// </summary>
        /// <param name="strFileName">저장될 파일의 전체 경로</param>
        private void SaveFile(string strFileName)
        {
            StreamWriter objSw = new StreamWriter(strFileName, false, System.Text.Encoding.Default);
            objSw.Write(this.txtMain.Text);
            objSw.Flush();
            objSw.Close();

            _IsTextChanged = false;
            this.Text = strFileName; // 제목에 파일명 출력
        }

        /// <summary>
        /// 텍스트 박스의 내용 비우기
        /// </summary>
        private void ClearText()
        {
            this.txtMain.ResetText(); // 텍스트박스 리셋   
            this.Text = "제목 없음 - 메모장";
            _IsTextChanged = false;
        }

        // 저장 또는 텍스트박스 클리어 또는 취소 기능 메서드
        private void SaveOrClearOrCancel(string strFlag)
        {
            DialogResult objDr = MessageBox.Show(
                this.Text + " " +
                " 파일의 내용이 변경되었습니다.\r\n" +
                "변경된 내용을 저장하시겠습니까?",
                "메모장",
                MessageBoxButtons.YesNoCancel,
                MessageBoxIcon.Exclamation);
            switch (objDr)
            {
                case DialogResult.Yes:
                    SaveText(); // 텍스트 저장
                    if (strFlag == "New")
                        ClearText(); // 텍스트 클리어(리셋)
                    else
                        OpenText(); // 열기
                    break;
                case DialogResult.No:
                    if (strFlag == "New")
                        ClearText(); // 텍스트 클리어(리셋)
                    else
                        OpenText(); // 열기
                    break;
                case DialogResult.Cancel:
                    break;
            }
        }

        // 열기 기능 메서드
        private void OpenText()
        {
            DialogResult objDr = ofdDotNetNote.ShowDialog();
            if (objDr != DialogResult.Cancel)
            {
                string strFileName = ofdDotNetNote.FileName;
                StreamReader objSr = new StreamReader(strFileName, System.Text.Encoding.Default);
                this.txtMain.Text = objSr.ReadToEnd();
                objSr.Close();

                _IsTextChanged = false;
                this.Text = strFileName; // 제목에 파일명 출력
            }
        }
        #endregion

        #region Event Handlers
        // 폼 로드 이벤트
        private void DotNetNote_Load(object sender, EventArgs e)
        {
            this.Width = 600;
            this.Height = 400;

            if (Registry.GetValue(@"HKEY_CURRENT_USER\Software\Hawaso\DotNetNote\", "Font-Family", "") != null)
            {
                // 레지스트리에 저장된 폰트 정보 가져오기
                Font fnt = new Font(
                  Convert.ToString(
                    Registry.GetValue(@"HKEY_CURRENT_USER\Software\Hawaso\DotNetNote\", "Font-Family", ""))
                  , Convert.ToSingle(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Hawaso\DotNetNote\", "Font-Size", "")));
                this.txtMain.Font = fnt;
            }

        }

        // 새로 만들기 메뉴
        private void miNew_Click(object sender, EventArgs e)
        {
            if (_IsTextChanged)
            {
                SaveOrClearOrCancel("New");
            }
            else
            {
                ClearText();
            }
        }

        // 텍스트 내용 변경시 발생
        private void txtMain_TextChanged(object sender, EventArgs e)
        {
            _IsTextChanged = true; // 텍스트 변경 적용
            miUndo.Enabled = true; // 취소 메뉴 활성화
            miCut.Enabled = true; // 잘라내기 메뉴 활성화
            miCopy.Enabled = true; // 복사 메뉴 활성화 
            miDel.Enabled = true; // 삭제 메뉴 활성화
            miFind.Enabled = true; // 찾기 메뉴 활성화
            miFindNext.Enabled = true; // 다음 찾기 메뉴 활성화
            miGo.Enabled = true; // 이동 메뉴 활성화
            if (txtMain.Text.Length == 0)
            {
              _IsTextChanged = false; 
            }
        }

        // 열기 메뉴
        private void miOpen_Click(object sender, EventArgs e)
        {
            if (_IsTextChanged)
            {
                SaveOrClearOrCancel("Open");
            }
            else
            {
                OpenText();
            }
        }

        // 저장 메뉴
        private void miSave_Click(object sender, EventArgs e)
        {
            SaveText(); // 저장 메서드 호출
        }

        // 다른 이름으로 저장
        private void miSaveAs_Click(object sender, EventArgs e)
        {
            DialogResult objDr = sfdDotNetNote.ShowDialog();
            if (objDr != DialogResult.Cancel)
            {
                string strFileName = sfdDotNetNote.FileName;
                SaveFile(strFileName);
            }
        }

        // 페이지 설정 메뉴
        private void miPageSetup_Click(object sender, EventArgs e)
        {
            //[1] PrintDocument.DocumentName = 문서 지정
            dnnPrintDocument.DocumentName = txtMain.Text;
            //[2] PageSetupDialog.Document = PrintDocument
            psdDotNetNote.Document = this.dnnPrintDocument;
            //[3] 페이지 설정 창 띄우기
            psdDotNetNote.ShowDialog();
        }

        // 인쇄 메뉴
        private void miPrint_Click(object sender, EventArgs e)
        {
            dnnPrintDocument.DocumentName = txtMain.Text;
            if (pdDotNetNote.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    dnnPrintDocument.Print();
                }
                catch
                {
                    MessageBox.Show(
                        "인쇄하는 도중에 에러가 발생했습니다.",
                        "인쇄 오류",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }

            }
        }

        // 페이지 인쇄 이벤트 핸들러
        private void dnnPrintDocument_PrintPage(
            object sender,
            System.Drawing.Printing.PrintPageEventArgs e)
        {
            StringReader objSr = new StringReader(this.txtMain.Text);

            // 현재 문서의 글꼴과 사이즈
            Font printFont =
                new Font(txtMain.Font.Name, txtMain.Font.Size);
            float linesPerPage = 0; // 페이지의 라인 수
            float yPos = 0; // 페이지 상단에서 떨어진 위치(문자열 출력)
            int count = 0; // 페이지 줄 번호

            float leftMargin = e.MarginBounds.Left; // 왼쪽 여백
            float topMargin = e.MarginBounds.Top; // 오른쪽 여백

            string line = null; // 각 행의 데이터 저장
            linesPerPage = // 페이지 당 라인 수 계산
                e.MarginBounds.Height /
                    printFont.GetHeight(e.Graphics);

            while (count < linesPerPage &&
                ((line = objSr.ReadLine()) != null))
            {
                yPos = topMargin +
                    (count * printFont.GetHeight(e.Graphics));
                e.Graphics.DrawString(
                    line,
                    printFont,
                    Brushes.Black,
                    leftMargin, yPos,
                    new StringFormat());
                count++;
            }

            if (line != null)
            {
                e.HasMorePages = true;
            }
            else
            {
                e.HasMorePages = false;
            }
            objSr.Close();
        }

        // 끝내기 메뉴
        private void miExit_Click(object sender, EventArgs e)
        {
            if (_IsTextChanged)
            {
                DialogResult objDr = MessageBox.Show(
                    this.Text + " " +
                    "파일의 내용이 변경되었습니다.\r\n" +
                    "변경된 내용을 저장하시겠습니까?",
                    "메모장",
                    MessageBoxButtons.YesNoCancel,
                    MessageBoxIcon.Exclamation);
                switch (objDr)
                {
                    case DialogResult.Yes:
                        SaveText(); // 텍스트 저장
                        this.Close(); // 종료
                        break;
                    case DialogResult.No:
                        this.Close(); // 종료
                        break;
                    case DialogResult.Cancel:
                        break;
                }   
            }
            else
            {
                Application.Exit(); // this.Close();
            }
        }

        // 실행 취소 메뉴
        private void miUndo_Click(object sender, EventArgs e)
        {
            if (this.txtMain.CanUndo)
            {
                this.txtMain.Undo();
            }
        }

        // 잘라내기 메뉴 구현
        private void miCut_Click(object sender, EventArgs e)
        {
            this.txtMain.Cut();
            //Clipboard.SetDataObject(txtMain.SelectedText);
            //txtMain.SelectedText = String.Empty;
        }

        // 복사 메뉴 구현
        private void miCopy_Click(object sender, EventArgs e)
        {
            this.txtMain.Copy();
            //Clipboard.SetDataObject(txtMain.SelectedText); // 복사
        }

        // 붙여넣기 메뉴 구현
        private void miPaste_Click(object sender, EventArgs e)
        {
            this.txtMain.Paste(); // 붙여넣기
            //[!] 클립보드의 내용이 텍스트 형식인지 검사 후 붙여넣기
            //if (Clipboard.GetDataObject().GetDataPresent(
            //    DataFormats.Text))
            //{
            //    // 클립보드의 내용을 텍스트 형식으로 변환 후 반환
            //    this.txtMain.SelectedText =
            //        Clipboard.GetDataObject().GetData(
            //        DataFormats.Text, true).ToString();
            //}
        }

        // 삭제 메뉴 구현
        private void miDel_Click(object sender, EventArgs e)
        {
            this.txtMain.SelectedText = String.Empty;
        }

        // 찾기 메뉴 구현
        private void miFind_Click(object sender, EventArgs e)
        {
            FrmFind f = new FrmFind(this);
            f.Show();
        }

        // 다음 찾기 메뉴 구현
        private void miFindNext_Click(object sender, EventArgs e)
        {
            miFind_Click(null, null);
        }

        // 바꾸기 메뉴 구현
        private void miReplace_Click(object sender, EventArgs e)
        {
            (new FrmReplace(this)).Show();
            //FrmReplace r = new FrmReplace(this);
            //r.Show();
        }

        // 이동 메뉴
        private void miGo_Click(object sender, EventArgs e)
        {
            int intLineLength = //전체 라인수
                this.txtMain.Lines.Length;
            int intCurrentLine = //현재 라인수
                Library.GetLineAndColumn(this.txtMain).Line;

            FrmGo go = new FrmGo(intLineLength, intCurrentLine);
            if (go.ShowDialog() == DialogResult.OK)
            {
                int intLineNum = 0;
                if (go.GetLine() != 1)
                {
                    for (int i = 0; i < go.GetLine() - 1; i++)
                    {
                        intLineNum +=
                            txtMain.Lines[i].Length + 2;
                    }
                }
                txtMain.SelectionStart = intLineNum;
                txtMain.ScrollToCaret();
            }
        }

        // 전체 선택 메뉴
        private void miSelectAll_Click(object sender, EventArgs e)
        {
            this.txtMain.SelectAll();
        }

        // 시간/날짜 메뉴 구현
        private void miTimeDate_Click(object sender, EventArgs e)
        {
          // 마우스 커서(캐럿) 자리에 시간/날짜 출력
          txtMain.SelectedText =
            String.Format("{0} {1}"
              , DateTime.Now.ToShortTimeString()
              , DateTime.Now.ToShortDateString());
        }

        // 자동 줄 바꿈 메뉴
        private void miWordWrap_Click(object sender, EventArgs e)
        {

            this.txtMain.WordWrap = !(this.txtMain.WordWrap);
            this.miWordWrap.Checked = !(this.miWordWrap.Checked);
            // 자동 줄 바꿈 체크 : 상태 표시줄 비활성화
            if (miWordWrap.Checked)
            {
              miStatus.Enabled = false;
            }
            else
            {
              miStatus.Enabled = true;
            }
        }
       
        // 글꼴 메뉴
        private void miFont_Click(object sender, EventArgs e)
        {
          fdDotNetNote.Font = txtMain.Font; // 폰트 다이얼로그 컨트롤에 현재 텍스트박스 글꼴 선택
          if (fdDotNetNote.ShowDialog() != DialogResult.Cancel)
          {
            txtMain.Font = fdDotNetNote.Font;
            // 윈도우 레지스트리에 현재 설정된 글꼴 저장
            Registry.SetValue(@"HKEY_CURRENT_USER\Software\Hawaso\DotNetNote\", "Font-Size", fdDotNetNote.Font.Size);
            Registry.SetValue(@"HKEY_CURRENT_USER\Software\Hawaso\DOtNetNOte\", "Font-Family", fdDotNetNote.Font.FontFamily.Name);
          }
        }

        // 상태 표시줄 메뉴
        private void miStatus_Click(object sender, EventArgs e)
        {
            if (this.dnnStatusStrip.Visible)
            {
                this.dnnStatusStrip.Visible = false;
                this.miStatus.Checked = false;
                this.txtMain.Height = this.Height - 55;
            }
            else
            {
                this.dnnStatusStrip.Visible = true;
                this.miStatus.Checked = true;
                int intLine =
                    Library.GetLineAndColumn(txtMain).Line;
                int intColumn =
                    Library.GetLineAndColumn(txtMain).Column;

                string strMsg = String.Format(
                    "Ln {0}, Col {1}", intLine, intColumn);

                this.toolStripStatusLabel2.Text = strMsg;
                this.txtMain.Height = this.txtMain.Height - 25;
            }
        }

        // 키보드 키 누른 후에 발생
        private void txtMain_KeyUp(object sender, KeyEventArgs e)
        {
            int intLine =
                Library.GetLineAndColumn(txtMain).Line;
            int intColumn =
                Library.GetLineAndColumn(txtMain).Column;

            string strMsg = String.Format(
                "Ln {0}, Col {1}", intLine, intColumn);

            this.toolStripStatusLabel2.Text = strMsg;
        }

        //[!] 도움말 항목 메뉴
        private void miHelp_Click(object sender, EventArgs e)
        {
            // 시스템(Windows) 디렉터리 경로
            string strDirectory =
                System.Environment.SystemDirectory;
            // Help 폴더 안의 Notepad.chm 파일 경로 : Parent
            strDirectory = // 한 단계 상위 경로 폴더 뽑아내기
                strDirectory.Substring(
                    0, strDirectory.LastIndexOf("\\"));
            strDirectory += @"\Help\Notepad.chm"; // Combine()
            // 파일이 있는지 확인 후 도움말 띄우기
            if (System.IO.File.Exists(strDirectory))
            {
                Help.ShowHelp(this, strDirectory);
            }
            else
            {
                MessageBox.Show(strDirectory +
                    "도움말 파일이 없습니다.",
                    "메모장",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }
 
        //[!] 메모장 정보 메뉴
        private void miAbout_Click(object sender, EventArgs e)
        {
          // FrmAbout 윈폼의 인스턴스 생성
          FrmAbout about = new FrmAbout();
          // 윈폼 개체의 showDialog() 메서드로 윈폼 띄우기
          about.ShowDialog(); // 모달(Modal) 폼
        }

        // 파일 드롭 지원 : txtMain.AllowDrop = true로 설정해야 함.
        private void txtMain_DragOver(object sender, DragEventArgs e)  {
          if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
            e.Effect = DragDropEffects.Copy;
          }
        }
        private void txtMain_DragDrop(object sender, DragEventArgs e) {
          if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
            string[] strFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
            StreamReader objSr = new StreamReader(
                strFiles[0], Encoding.Default);
            this.txtMain.Clear();
            this.txtMain.Text = objSr.ReadToEnd();
            objSr.Close();
          }
        }
        private void txtMain_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) {
            if (e.EscapePressed) {
                e.Action = DragAction.Cancel;
            }
        }
        #endregion

        private void miPreview_Click(object sender, EventArgs e)
        {
            // 미리보기
            this.dnnPrintPreviewDialog.Document = this.dnnPrintDocument;
            this.dnnPrintPreviewDialog.ShowDialog();
        }

    }
}





< 실행결과 >





--> DotNetNote.cs에서 형광펜으로 색칠된 부분의 2줄 코드를 작성하여 "인쇄 미리 보기" 기능을 구현함.





Posted by holland14
:

* DotNetNote.cs [디자인]의 TextBox인 "txtMain"의 속성에서 "AllowDrop ->True"로 설정함. 그리고 "txtMain"의 '이벤트'속성 중 "DragDrop -> txtMain_DragDrop", "DragOver -> txtMain_DragOver", "QueryContinueDrag -> txtMain_QueryContinueDrag"로 변경하고, 아래 "DotNetNote.cs"의 형광펜 칠한 부분의 코드를 작성하여 "파일 드래그&드롭" 실행.

==> Program.cs



using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace DotNetNote
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new DotNetNote());
        }
    }
}




==============================================================================================




==> DotNetNote.cs



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Win32;

namespace DotNetNote
{
    public partial class DotNetNote : Form
    {
        #region Constructors
        public DotNetNote()
        {
            InitializeComponent();
        }
        #endregion

        #region Private Member Variables
        private bool _IsTextChanged; // 텍스트 변경 여부
        #endregion

        #region Private Methods
        /// <summary>
        /// 파일을 저장할지 결정 메서드
        /// </summary>
        private void SaveText()
        {
            if (this.Text == "제목 없음 - 메모장")
            {
                DialogResult objDr = sfdDotNetNote.ShowDialog();
                if (objDr != DialogResult.Cancel)
                {
                    string strFileName = sfdDotNetNote.FileName;
                    SaveFile(strFileName);
                }
            }
            else
            {
                string strFileName = this.Text; // 파일 전체 이름
                SaveFile(strFileName);
            }
        }

        /// <summary>
        /// 실제 파일을 저장하는 메서드
        /// </summary>
        /// <param name="strFileName">저장될 파일의 전체 경로</param>
        private void SaveFile(string strFileName)
        {
            StreamWriter objSw = new StreamWriter(strFileName, false, System.Text.Encoding.Default);
            objSw.Write(this.txtMain.Text);
            objSw.Flush();
            objSw.Close();

            _IsTextChanged = false;
            this.Text = strFileName; // 제목에 파일명 출력
        }

        /// <summary>
        /// 텍스트 박스의 내용 비우기
        /// </summary>
        private void ClearText()
        {
            this.txtMain.ResetText(); // 텍스트박스 리셋   
            this.Text = "제목 없음 - 메모장";
            _IsTextChanged = false;
        }

        // 저장 또는 텍스트박스 클리어 또는 취소 기능 메서드
        private void SaveOrClearOrCancel(string strFlag)
        {
            DialogResult objDr = MessageBox.Show(
                this.Text + " " +
                " 파일의 내용이 변경되었습니다.\r\n" +
                "변경된 내용을 저장하시겠습니까?",
                "메모장",
                MessageBoxButtons.YesNoCancel,
                MessageBoxIcon.Exclamation);
            switch (objDr)
            {
                case DialogResult.Yes:
                    SaveText(); // 텍스트 저장
                    if (strFlag == "New")
                        ClearText(); // 텍스트 클리어(리셋)
                    else
                        OpenText(); // 열기
                    break;
                case DialogResult.No:
                    if (strFlag == "New")
                        ClearText(); // 텍스트 클리어(리셋)
                    else
                        OpenText(); // 열기
                    break;
                case DialogResult.Cancel:
                    break;
            }
        }

        // 열기 기능 메서드
        private void OpenText()
        {
            DialogResult objDr = ofdDotNetNote.ShowDialog();
            if (objDr != DialogResult.Cancel)
            {
                string strFileName = ofdDotNetNote.FileName;
                StreamReader objSr = new StreamReader(strFileName, System.Text.Encoding.Default);
                this.txtMain.Text = objSr.ReadToEnd();
                objSr.Close();

                _IsTextChanged = false;
                this.Text = strFileName; // 제목에 파일명 출력
            }
        }
        #endregion

        #region Event Handlers
        // 폼 로드 이벤트
        private void DotNetNote_Load(object sender, EventArgs e)
        {
            this.Width = 600;
            this.Height = 400;

            if (Registry.GetValue(@"HKEY_CURRENT_USER\Software\Hawaso\DotNetNote\", "Font-Family", "") != null)
            {
                // 레지스트리에 저장된 폰트 정보 가져오기
                Font fnt = new Font(
                  Convert.ToString(
                    Registry.GetValue(@"HKEY_CURRENT_USER\Software\Hawaso\DotNetNote\", "Font-Family", ""))
                  , Convert.ToSingle(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Hawaso\DotNetNote\", "Font-Size", "")));
                this.txtMain.Font = fnt;
            }

        }

        // 새로 만들기 메뉴
        private void miNew_Click(object sender, EventArgs e)
        {
            if (_IsTextChanged)
            {
                SaveOrClearOrCancel("New");
            }
            else
            {
                ClearText();
            }
        }

        // 텍스트 내용 변경시 발생
        private void txtMain_TextChanged(object sender, EventArgs e)
        {
            _IsTextChanged = true; // 텍스트 변경 적용
            miUndo.Enabled = true; // 취소 메뉴 활성화
            miCut.Enabled = true; // 잘라내기 메뉴 활성화
            miCopy.Enabled = true; // 복사 메뉴 활성화 
            miDel.Enabled = true; // 삭제 메뉴 활성화
            miFind.Enabled = true; // 찾기 메뉴 활성화
            miFindNext.Enabled = true; // 다음 찾기 메뉴 활성화
            miGo.Enabled = true; // 이동 메뉴 활성화
            if (txtMain.Text.Length == 0)
            {
              _IsTextChanged = false; 
            }
        }

        // 열기 메뉴
        private void miOpen_Click(object sender, EventArgs e)
        {
            if (_IsTextChanged)
            {
                SaveOrClearOrCancel("Open");
            }
            else
            {
                OpenText();
            }
        }

        // 저장 메뉴
        private void miSave_Click(object sender, EventArgs e)
        {
            SaveText(); // 저장 메서드 호출
        }

        // 다른 이름으로 저장
        private void miSaveAs_Click(object sender, EventArgs e)
        {
            DialogResult objDr = sfdDotNetNote.ShowDialog();
            if (objDr != DialogResult.Cancel)
            {
                string strFileName = sfdDotNetNote.FileName;
                SaveFile(strFileName);
            }
        }

        // 페이지 설정 메뉴
        private void miPageSetup_Click(object sender, EventArgs e)
        {
            //[1] PrintDocument.DocumentName = 문서 지정
            dnnPrintDocument.DocumentName = txtMain.Text;
            //[2] PageSetupDialog.Document = PrintDocument
            psdDotNetNote.Document = this.dnnPrintDocument;
            //[3] 페이지 설정 창 띄우기
            psdDotNetNote.ShowDialog();
        }

        // 인쇄 메뉴
        private void miPrint_Click(object sender, EventArgs e)
        {
            dnnPrintDocument.DocumentName = txtMain.Text;
            if (pdDotNetNote.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    dnnPrintDocument.Print();
                }
                catch
                {
                    MessageBox.Show(
                        "인쇄하는 도중에 에러가 발생했습니다.",
                        "인쇄 오류",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }

            }
        }

        // 페이지 인쇄 이벤트 핸들러
        private void dnnPrintDocument_PrintPage(
            object sender,
            System.Drawing.Printing.PrintPageEventArgs e)
        {
            StringReader objSr = new StringReader(this.txtMain.Text);

            // 현재 문서의 글꼴과 사이즈
            Font printFont =
                new Font(txtMain.Font.Name, txtMain.Font.Size);
            float linesPerPage = 0; // 페이지의 라인 수
            float yPos = 0; // 페이지 상단에서 떨어진 위치(문자열 출력)
            int count = 0; // 페이지 줄 번호

            float leftMargin = e.MarginBounds.Left; // 왼쪽 여백
            float topMargin = e.MarginBounds.Top; // 오른쪽 여백

            string line = null; // 각 행의 데이터 저장
            linesPerPage = // 페이지 당 라인 수 계산
                e.MarginBounds.Height /
                    printFont.GetHeight(e.Graphics);

            while (count < linesPerPage &&
                ((line = objSr.ReadLine()) != null))
            {
                yPos = topMargin +
                    (count * printFont.GetHeight(e.Graphics));
                e.Graphics.DrawString(
                    line,
                    printFont,
                    Brushes.Black,
                    leftMargin, yPos,
                    new StringFormat());
                count++;
            }

            if (line != null)
            {
                e.HasMorePages = true;
            }
            else
            {
                e.HasMorePages = false;
            }
            objSr.Close();
        }

        // 끝내기 메뉴
        private void miExit_Click(object sender, EventArgs e)
        {
            if (_IsTextChanged)
            {
                DialogResult objDr = MessageBox.Show(
                    this.Text + " " +
                    "파일의 내용이 변경되었습니다.\r\n" +
                    "변경된 내용을 저장하시겠습니까?",
                    "메모장",
                    MessageBoxButtons.YesNoCancel,
                    MessageBoxIcon.Exclamation);
                switch (objDr)
                {
                    case DialogResult.Yes:
                        SaveText(); // 텍스트 저장
                        this.Close(); // 종료
                        break;
                    case DialogResult.No:
                        this.Close(); // 종료
                        break;
                    case DialogResult.Cancel:
                        break;
                }   
            }
            else
            {
                Application.Exit(); // this.Close();
            }
        }

        // 실행 취소 메뉴
        private void miUndo_Click(object sender, EventArgs e)
        {
            if (this.txtMain.CanUndo)
            {
                this.txtMain.Undo();
            }
        }

        // 잘라내기 메뉴 구현
        private void miCut_Click(object sender, EventArgs e)
        {
            this.txtMain.Cut();
            //Clipboard.SetDataObject(txtMain.SelectedText);
            //txtMain.SelectedText = String.Empty;
        }

        // 복사 메뉴 구현
        private void miCopy_Click(object sender, EventArgs e)
        {
            this.txtMain.Copy();
            //Clipboard.SetDataObject(txtMain.SelectedText); // 복사
        }

        // 붙여넣기 메뉴 구현
        private void miPaste_Click(object sender, EventArgs e)
        {
            this.txtMain.Paste(); // 붙여넣기
            //[!] 클립보드의 내용이 텍스트 형식인지 검사 후 붙여넣기
            //if (Clipboard.GetDataObject().GetDataPresent(
            //    DataFormats.Text))
            //{
            //    // 클립보드의 내용을 텍스트 형식으로 변환 후 반환
            //    this.txtMain.SelectedText =
            //        Clipboard.GetDataObject().GetData(
            //        DataFormats.Text, true).ToString();
            //}
        }

        // 삭제 메뉴 구현
        private void miDel_Click(object sender, EventArgs e)
        {
            this.txtMain.SelectedText = String.Empty;
        }

        // 찾기 메뉴 구현
        private void miFind_Click(object sender, EventArgs e)
        {
            FrmFind f = new FrmFind(this);
            f.Show();
        }

        // 다음 찾기 메뉴 구현
        private void miFindNext_Click(object sender, EventArgs e)
        {
            miFind_Click(null, null);
        }

        // 바꾸기 메뉴 구현
        private void miReplace_Click(object sender, EventArgs e)
        {
            (new FrmReplace(this)).Show();
            //FrmReplace r = new FrmReplace(this);
            //r.Show();
        }

        // 이동 메뉴
        private void miGo_Click(object sender, EventArgs e)
        {
            int intLineLength = //전체 라인수
                this.txtMain.Lines.Length;
            int intCurrentLine = //현재 라인수
                Library.GetLineAndColumn(this.txtMain).Line;

            FrmGo go = new FrmGo(intLineLength, intCurrentLine);
            if (go.ShowDialog() == DialogResult.OK)
            {
                int intLineNum = 0;
                if (go.GetLine() != 1)
                {
                    for (int i = 0; i < go.GetLine() - 1; i++)
                    {
                        intLineNum +=
                            txtMain.Lines[i].Length + 2;
                    }
                }
                txtMain.SelectionStart = intLineNum;
                txtMain.ScrollToCaret();
            }
        }

        // 전체 선택 메뉴
        private void miSelectAll_Click(object sender, EventArgs e)
        {
            this.txtMain.SelectAll();
        }

        // 시간/날짜 메뉴 구현
        private void miTimeDate_Click(object sender, EventArgs e)
        {
          // 마우스 커서(캐럿) 자리에 시간/날짜 출력
          txtMain.SelectedText =
            String.Format("{0} {1}"
              , DateTime.Now.ToShortTimeString()
              , DateTime.Now.ToShortDateString());
        }

        // 자동 줄 바꿈 메뉴
        private void miWordWrap_Click(object sender, EventArgs e)
        {

            this.txtMain.WordWrap = !(this.txtMain.WordWrap);
            this.miWordWrap.Checked = !(this.miWordWrap.Checked);
            // 자동 줄 바꿈 체크 : 상태 표시줄 비활성화
            if (miWordWrap.Checked)
            {
              miStatus.Enabled = false;
            }
            else
            {
              miStatus.Enabled = true;
            }
        }
       
        // 글꼴 메뉴
        private void miFont_Click(object sender, EventArgs e)
        {
          fdDotNetNote.Font = txtMain.Font; // 폰트 다이얼로그 컨트롤에 현재 텍스트박스 글꼴 선택
          if (fdDotNetNote.ShowDialog() != DialogResult.Cancel)
          {
            txtMain.Font = fdDotNetNote.Font;
            // 윈도우 레지스트리에 현재 설정된 글꼴 저장
            Registry.SetValue(@"HKEY_CURRENT_USER\Software\Hawaso\DotNetNote\", "Font-Size", fdDotNetNote.Font.Size);
            Registry.SetValue(@"HKEY_CURRENT_USER\Software\Hawaso\DOtNetNOte\", "Font-Family", fdDotNetNote.Font.FontFamily.Name);
          }
        }

        // 상태 표시줄 메뉴
        private void miStatus_Click(object sender, EventArgs e)
        {
            if (this.dnnStatusStrip.Visible)
            {
                this.dnnStatusStrip.Visible = false;
                this.miStatus.Checked = false;
                this.txtMain.Height = this.Height - 55;
            }
            else
            {
                this.dnnStatusStrip.Visible = true;
                this.miStatus.Checked = true;
                int intLine =
                    Library.GetLineAndColumn(txtMain).Line;
                int intColumn =
                    Library.GetLineAndColumn(txtMain).Column;

                string strMsg = String.Format(
                    "Ln {0}, Col {1}", intLine, intColumn);

                this.toolStripStatusLabel2.Text = strMsg;
                this.txtMain.Height = this.txtMain.Height - 25;
            }
        }

        // 키보드 키 누른 후에 발생
        private void txtMain_KeyUp(object sender, KeyEventArgs e)
        {
            int intLine =
                Library.GetLineAndColumn(txtMain).Line;
            int intColumn =
                Library.GetLineAndColumn(txtMain).Column;

            string strMsg = String.Format(
                "Ln {0}, Col {1}", intLine, intColumn);

            this.toolStripStatusLabel2.Text = strMsg;
        }

        //[!] 도움말 항목 메뉴
        private void miHelp_Click(object sender, EventArgs e)
        {
            // 시스템(Windows) 디렉터리 경로
            string strDirectory =
                System.Environment.SystemDirectory;
            // Help 폴더 안의 Notepad.chm 파일 경로 : Parent
            strDirectory = // 한 단계 상위 경로 폴더 뽑아내기
                strDirectory.Substring(
                    0, strDirectory.LastIndexOf("\\"));
            strDirectory += @"\Help\Notepad.chm"; // Combine()
            // 파일이 있는지 확인 후 도움말 띄우기
            if (System.IO.File.Exists(strDirectory))
            {
                Help.ShowHelp(this, strDirectory);
            }
            else
            {
                MessageBox.Show(strDirectory +
                    "도움말 파일이 없습니다.",
                    "메모장",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }
 
        //[!] 메모장 정보 메뉴
        private void miAbout_Click(object sender, EventArgs e)
        {
          // FrmAbout 윈폼의 인스턴스 생성
          FrmAbout about = new FrmAbout();
          // 윈폼 개체의 showDialog() 메서드로 윈폼 띄우기
          about.ShowDialog(); // 모달(Modal) 폼
        }

        // 파일 드롭 지원 : txtMain.AllowDrop = true로 설정해야 함.
        private void txtMain_DragOver(object sender, DragEventArgs e)  {
          if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
            e.Effect = DragDropEffects.Copy;
          }
        }
        private void txtMain_DragDrop(object sender, DragEventArgs e) {
          if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
            string[] strFiles = (string[])e.Data.GetData(DataFormats.FileDrop);
            StreamReader objSr = new StreamReader(
                strFiles[0], Encoding.Default);
            this.txtMain.Clear();
            this.txtMain.Text = objSr.ReadToEnd();
            objSr.Close();
          }
        }
        private void txtMain_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) {
            if (e.EscapePressed) {
                e.Action = DragAction.Cancel;
            }
        }
        #endregion

        private void miPreview_Click(object sender, EventArgs e)
        {
            // 미리보기
            this.dnnPrintPreviewDialog.Document = this.dnnPrintDocument;
            this.dnnPrintPreviewDialog.ShowDialog();
        }
    }
}






< 실행결과 >

--> 속성 중 "이벤트"속성에서 아래 그림과 같이 3개를 변경함.





















Posted by holland14
:


==> Program.cs




using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Sample.FrmNotepad());
        }
    }
}





==============================================================================================




==> FrmNotepad.cs




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;
using System.IO; // 파일 처리

namespace MyWinForms.Sample
{
    public partial class FrmNotepad : Form
    {
        public FrmNotepad()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "텍스트파일|*.txt"; // 코드레벨 설정
            if (openFileDialog1.ShowDialog() == DialogResult.OK) {
                // 텍스트 파일 열기
                StreamReader sr = new StreamReader(
                    openFileDialog1.FileName, Encoding.Default);
                // 데이터 읽어오기
                txtNote.Text = sr.ReadToEnd(); // 텍스트 모두 열기
                // 파일 닫기
                sr.Close();
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "텍스트파일|*.txt";
            if (saveFileDialog1.ShowDialog() != DialogResult.Cancel) {
                StreamWriter sw = new StreamWriter(
                    saveFileDialog1.FileName, false, Encoding.Default);
                sw.Write(txtNote.Text);
                sw.Close();
            }
        }

        private void btnClick(object sender, EventArgs e)
        {
            Button btn = sender as Button;
            if (btn == btnCopy) // 복사 버튼이라면
            {
                // 클립보드에 선택된 텍스트를 복사(저장)
                //Clipboard.SetText(this.txtNote.SelectedText);
                // 객체형으로 저장
                Clipboard.SetDataObject(txtNote.SelectedText, true);
            }
            else
            {
                // 현재 클립보드의 텍스트를 붙여넣기
                //this.txtNote.Text = Clipboard.GetText();
                IDataObject ido = Clipboard.GetDataObject();
                if (ido.GetDataPresent(typeof(string)))
                {
                    txtNote.Text = (string)ido.GetData(typeof(string));
                }
            }
        }

    }
}






< 실행결과 >

--> 아래 텍스트에서 특정부분을 선택하여 "복사"버튼을 누름.





--> "붙여넣기"버튼을 눌렀을 때 복사하였던 부분이 출력됨.




Posted by holland14
:


* '도구상자 -> 모든 Windows Forms'에서 "ToolTip" 드래그&드롭 --> 도구상자에서 하나 추가한 'Buton'컨트롤의 속성 중 "기타"에서 "toolTip1의 ToolTip -> 풍선도움말"로 변경하고, 폼 클릭 후 폼의 속성 중 "기타"에서 "toolTip1의 ToolTip -> 폼의 풍선도움말"로  텍스트를 입력한다.



==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Controls.FrmToolTip());
        }
    }
}




==============================================================================================




==> MainForm.cs




// 툴팁 관련
        private void 툴팁ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            (new MyWinForms.Controls.FrmToolTip()).Show();
        }




< 실행결과 >

--> 마우스 커서를 "button1"에 올렸을 때 "풍선도움말" 툴팁이 나타난다.





--> 마우스 커서를 "FrmToolTip" 폼에 올렸을 때 "폼의 풍선도움말" 툴팁이 나타난다.






Posted by holland14
:


* 도구상자의 "모든 Windows Forms"에서 "TabControl'을 폼에 드래그&드롭 --> 속성에서"TabPages"클릭한 후 "TabPage 컬렉션 편집기"에서 텍스트내용 변경('일반'/'보안')
폼에 그룹박스(GroupBox) 한개 만든 후 "TrackBar"도 그룹박스 안에 드래그&드롭 후 '속성'에서 "Orientation -> Vertical"로 변경.




==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Controls.FrmTabControl());
        }
    }
}




==============================================================================================




==> MainForm.cs



        // 탭컨트롤 관련
        private void 탭컨트롤ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            (new MyWinForms.Controls.FrmTabControl()).Show();
        }




==============================================================================================




==> FrmTabControl.cs



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;
using System.IO;
using Microsoft.Win32;

namespace MyWinForms.Controls
{
    public partial class FrmTabControl : Form
    {
        public FrmTabControl()
        {
            InitializeComponent();
        }

        private void tbLevel_Scroll(object sender, EventArgs e)
        {
            switch (this.tbLevel.Value)
            {
                case 0:
                    lblDisplay.Text = "낮음";
                    break;
                case 1:
                    lblDisplay.Text = "보통";
                    break;
                case 2:
                    lblDisplay.Text = "높음";
                    break;
                default:
                    break;
            }
        }

        private void FrmTabControl_Load(object sender, EventArgs e)
        {
            LoadHome();
            LoadLevel();
            tbLevel_Scroll(null, null);
        }

        private void LoadLevel()
        {
            // Windows 레지스트리 정보 읽어오기
            RegistryKey r = Registry.CurrentUser.OpenSubKey(dir);
            if (r != null)
            {
                tbLevel.Value = Convert.ToInt32(r.GetValue("Value"));
                r.Close();
            }           
        }

        private void LoadHome()
        {
            if (File.Exists("C:\\Temp\\Home.dat"))
            {
                StreamReader sr = new StreamReader("C:\\Temp\\Home.dat");
                this.txtHome.Text = sr.ReadLine();
                sr.Close();
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            string msg = "홈페이지 : " + txtHome.Text;
            msg += "\n보안수준 : " + lblDisplay.Text;

            MessageBox.Show(msg, "옵션정보", MessageBoxButtons.OK, MessageBoxIcon.Information);

            // 홈페이지 정보 : 파일에 저장
            SaveHome(txtHome.Text);

            // 보안수준 정보 : 레지스트리에 저장
            SaveLevel(tbLevel.Value);

            this.Close();

        }

        private string dir = "Software\\Hawaso\\MyWinForms";
        private void SaveLevel(int p)
        {
            // Windows 레지스트리에 데이터 저장
            RegistryKey r = Registry.CurrentUser.OpenSubKey(dir);
            if (r == null)
            {
               r = Registry.CurrentUser.CreateSubKey(dir);
            }
            r.SetValue("Value", tbLevel.Value
                , RegistryValueKind.DWord); // 0, 1, 2 값 중 하나 저장

            r.Close();
        }

        private void SaveHome(string p)
        {
            StreamWriter sw = new StreamWriter("C:\\Temp\\Home.dat");
            sw.WriteLine(txtHome.Text);
            sw.Close();
        }
    }
}




< 실행결과 >









--> 파일(Home.dat)에 저장된 홈페이지 정보(www.hawaso.com)




--> 레지스트리에 저장된 데이터






Posted by holland14
:


* 앞의 예제에서 했던대로 "리스트뷰(ListView)"는 "Columns"속성에 들어가서 "컬렉션 편집기"로 편집     --> 'View'속성을 "Details"로 바꿈.
* "트리뷰(TreeView)"는 앞의 예제방법과는 다르게 'FrmMyComputer.cs [디자인]'에서 "속성"부분을 변경하지 않았다. 대신 아래의 'FrmMyComputer.cs'에서 형광색 칠해진 코드부분으로 "트리뷰(TreeView)"를 구현하였다.


==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyWinForms.Sample.FrmMyComputer());
        }
    }
}




==============================================================================================




==> FrmMyComputer.cs




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;
using System.Management;
using System.IO;

namespace MyWinForms.Sample
{
    public partial class FrmMyComputer : Form
    {
        public FrmMyComputer()
        {
            InitializeComponent();
        }

        private void FrmMyComputer_Load(object sender, EventArgs e)
        {
            DisplayData();
        }
        // 전체 폴더 목록을 왼쪽 트리뷰에 출력
        private void DisplayData()
        {
            this.treeView1.Nodes.Add(new TreeNode("니 컴퓨터"));

            var q =
                new ManagementObjectSearcher(
                    "SELECT * From Win32_LogicalDisk");
            var arr = q.Get(); // 목록 받아오기

            foreach (var item in arr)
            {
                this.treeView1.Nodes[0].Nodes.Add(
                    new TreeNode(item["Name"].ToString())); // 자식 노드로 추가
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (this.treeView1.SelectedNode.Text != "니 컴퓨터")
            {
                DisplayList(treeView1.SelectedNode.Text + @"\");
            }
        }
        // 왼쪽 트리뷰에서 C, D 선택시 오른쪽에 해당 폴더 내용출력
        private void DisplayList(string dir) {
            this.listView1.Items.Clear(); // 클리어
            if (!Directory.Exists(dir)) {
                MessageBox.Show("드라이브가 없거나 로드 불가");
            }
            else {
                DirectoryInfo di = new DirectoryInfo(dir);
                foreach (var item in di.GetDirectories()) // 폴더목록
                {
                    listView1.Items.Add(
                        new ListViewItem(new string[]{item.Name, ""}));
                }
                foreach (var item in di.GetFiles()) // 파일목록
                {
                    listView1.Items.Add(
                        new ListViewItem(new string[] {
                            item.Name, item.Length.ToString() }));
                }
            }
        }
    }
}





< 실행결과 >

--> "리스트뷰(ListView)" : "Columns"속성에서 "컬렉션 편집기"로 편집  






--> "리스트뷰(ListView)" : "Columns"속성에서 "컬렉션 편집기"로 편집 후 'View'속성을 "Details"로 바꿈.




--> 실행 후 "C : "를 클릭하였을 때 "리스트뷰(ListView)"에 C드라이브에 있는 '폴더'목록들과 '파일'목록들이 출력되었다.




--> "A : " 또는 "E : " 또는 "F : "를 클릭하였을 때는 존재하는 파일 또는 폴더가 없으므로 위에 있는 "FrmMyComputer.cs"에서 구현한대로 "MessageBox"가 출력됨.





Posted by holland14
:

* 트리뷰(TreeView)는 윈도우 탐색기의 좌측에 위치해 있는 부분을 말한다.

'도구상자'의 '모든 Windows Forms'에서 "TreeView"를 폼에 드래그 & 드롭 --> "Nodes"속성에 들어가서 "TreeNode 편집기"로 편집("루트추가"/"자식추가"/각 노드의 "Text"속성에 텍스트입력)


==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Controls.FrmTreeView());
        }
    }
}




==============================================================================================




==> FrmTreeView.cs



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 MyWinForms.Controls
{
    public partial class FrmTreeView : Form
    {
        public FrmTreeView()
        {
            InitializeComponent();
        }

        private void FrmTreeView_Load(object sender, EventArgs e)
        {
            //
            this.treeView1.Nodes[0].Nodes[1].Nodes.Add("Program");
            this.treeView1.Nodes[0].Nodes[1].Nodes[0].Nodes.Add("SQL");
        }
    }
}





< 실행결과 >

--> "TreeView"의 "Nodes"속성에 들어가서 "TreeNode 편집기"로 편집












Posted by holland14
:

* 리스트뷰(ListView)는 윈도우탐색기의 위쪽에 위치한 부분을 말한다.

'도구상자'의 '모든 Windows Forms'에서 "ListView"를 폼에 드래그 & 드롭 --> "Columns"속성에 들어가서 "컬렉션 편집기"로 편집 --> 'View'속성을 "Details"로 바꿈.



==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Controls.FrmListView());
        }
    }
}




==============================================================================================




==> FrmListView.cs




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 MyWinForms.Controls
{
    public partial class FrmListView : Form
    {
        public FrmListView()
        {
            InitializeComponent();
        }

        private void FrmListView_Load(object sender, EventArgs e)
        {
            // 국어/영어/총점을 리스트뷰에 출력
            string[,] arr =
                new string[,]
                {
                    {"100", "100", "200"},
                    {"90", "90", "180"},
                    {"80", "80", "160"}
                };

            // 3개의 레코드를 리스트뷰에 출력
            string[] arr1 = new string[] { "100", "100", "200" };
            string[] arr2 = new string[] { "90", "90", "180" };
            string[] arr3 = new string[] { "80", "80", "160" };

            // 입력
            this.lstScore.Items.Add(new ListViewItem(arr1)); //[1]번째 방법   

            ListViewItem lvi = new ListViewItem(arr2);// [2]번째 방법
            this.lstScore.Items.Add(lvi);

            this.lstScore.Items.Add(
                new ListViewItem(new string[] { "80", "80", "160" })); //[3]번째 방법
           
        }
    }
}





< 실행결과 >

--> "ListView"의 "Columns"속성에서 "컬렉션 편집기"로 내용변경





--> "View"속성도 Details로 변경




--> 출력화면




Posted by holland14
:


* '도구상자'의 '모든 Windows Forms'에서 'HScrollBar'와 'VScrollBar'를 폼에 드래그 & 드롭하여 스크롤 기능 추가함. 폼에 하나 추가한 'OpenFileDialog'의 "Filter"속성을 " 비트맵|*.tmp|JGP|*.jpg|JPEG|*.jpeg|PNG|*.png"로 하여 파일을 열 때 원하는 이미지 파일확장자명 만 나오게 된다.



==> Program.cs



using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace MyWinForms
{
    static class Program
    {
        /// <summary>
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Sample.FrmImageViewer());
        }
    }
}




==============================================================================================




==> MainForm.cs


        // 이미지뷰어 관련(PictureBox와 OpenFileDialog 사용)
        private void miImageViewer_Click(object sender, EventArgs e)
        {
            (new FrmImageViewer()).Show();
        }




==============================================================================================




==> FrmImageViewer.cs



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 MyWinForms.Sample
{
    public partial class FrmImageViewer : Form
    {
        public FrmImageViewer()
        {
            InitializeComponent();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (ofdImage.ShowDialog() != DialogResult.Cancel)
            {
                this.picImage.ImageLocation = ofdImage.FileName;
            }
        }

        private void FrmImageViewer_Load(object sender, EventArgs e)
        {
            // 픽쳐박스의 기본 크기는 50*50
            p.X = hScrollBar1.Value;
            p.Y = vScrollBar1.Value;
            this.picImage.Size = new Size(p);
        }

        Point p; // 포인터형 변수 : X, Y값을 보관
        private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            p.X = hScrollBar1.Value * 2;
            this.picImage.Size = new Size(p);
        }

        private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
            p.Y = vScrollBar1.Value * 2;
            this.picImage.Size = new Size(p);
        }
    }
}




< 실행결과 >





--> '도구상자'의 '모든 Windows Forms'에서 'HScrollBar'와 'VScrollBar'를 폼에 드래그 & 드롭하여 스크롤 기능 추가함.




--> '사진 열기'버튼을 누른 후 열린 "열기"창(OpenFileDialog)에서 컴퓨터에 저장해놨던 JPG파일을 선택함.





--> 선택한 JPG파일을 열었을 때 화면. 'HScrollBar'와 'VScrollBar'를 움직여 이미지 크기 조작가능.







Posted by holland14
: