메모장 똑같이 구현하기. C#프로그래밍




메모장 구현 설명:

도구상자에서 각각의 컨트롤을 배치후 이름 변경.

 

저장하기:

해당 버튼 컨트롤의 Click이벤트에

   StreamWriter SaveText = new StreamWriter(FileName, false, System.Text.Encoding.Default);

            SaveText.Write(menu_File.Text);

            SaveText.Close();

StreamWriter (텍스트 쓰기 ) 클래스를 사용해

지정된 된 인코딩과 기본 버퍼 크기를 사용 하 여 지정된 된 파일에 대 한

 해당 파일이 있으면 덮어쓰거나 추가합니다. 해당 파일이 없으면 이 생성자는 새 파일을 만듭니다.

 

파일열기:

    StreamReader sr = new StreamReader(FileName, System.Text.Encoding.Default);

                menu_File.Text = sr.ReadToEnd();

                menu_File.SelectionStart = 0;

                sr.Close();

StreamReader (텍스트 읽기) 클래스를 사용해

지정된 문자 인코딩을 사용하여 지정된 파일 이름에 대해 System.IO.StreamReader 클래스의 새 인스턴스를 초기화합니다.

 

페이지설정:

using System.Drawing.Printing; 추가

페이지설정 컨트롤 버튼 눌렸을때 발생하는 이벤트에

 PrintDocument pd = new PrintDocument();

            pd.DocumentName = menu_File.Text;

            pageSetupDialog1.Document = pd;

            pageSetupDialog1.ShowDialog();

PrintDocument 변수를 생성하고 리치박스 문자를 인자로넘긴후

pageSetupDialog1 설정후 보여주기.

 

편집 - 실행 취소, 되돌리기, 잘라내기, 복사, 붙여넣기, 삭제

RichTextBox.Undo(); Redo(), Cut(); Copy(); Paste(); Cut(); 메소드 각각 사용.

 

찾기: 해당윈폼만든후 컨트롤배치.

생성자에서 메모장윈폼의 RichTextBox 인자로넘겨 변수로 Set한다.

인자로넘겨받은 RichTextBox Find()함수를 통해서 찾기윈폼의 TextBox  Text 위치정보를 가져온다.

그후에 리치박스의 SelectionStart 위치를 갱신한다.

 

바꾸기: 찾기와 동일한 방식으로 텍스쳐를 찾은후

리치박스의.Replace함수를 통해 바꿀내용과 찾을 내용의 텍스쳐를 스왑한후 새문자열을 반환한걸

리치박스의.SelectedText 넘겨준다.

 

 

이동: 해당윈폼을 만든후 컨트롤배치한후에

생성자에 메모장윈폼을 인자로 넘겨 받는다.

줄번호의 숫자문자열을 IsDigt함수를통해 숫자만 입력했다면 int형으로바꿔 메모장윈품.moveLine 대입한다.

RichTextBox 문자열에 "\n"의 개수를 새어 해당 개수마다 개행카운트를 증가시킨후 만약 움직일 moveLine

개행카운트가 같다면 RichTextBox.SelectionStart변수에 i만큼 반복한 위치를 넘긴다.

 

 

 

소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Printing;
 
namespace MemoJang
{
    public partial class Form1 : Form
    {
        // 전역 변수
        public TextBox tb;
        private bool EditText = false;
        private bool SaveCheck = false;
        private Font printFont;
        private string streamToPrint = null;
        public int moveLine = 0;
        //폼 파일 객체
        Go GoForm;
        Find FindForm;
        Change ChangeForm;
 
 
        public Form1()
        {
            InitializeComponent();
        }
 
 
        #region 상단 메뉴
        private void menu_File1_Click(object sender, EventArgs e)
        {
 
        }
        private void menu_Edit_Click(object sender, EventArgs e)
        {
 
        }
        private void menu_Ori_Click(object sender, EventArgs e)
        {
 
        }
        #endregion
 
 
        #region 메뉴 - 파일
        // 파일
        // 상단 메뉴
        private void menu_NewFile_Click_1(object sender, EventArgs e)
        {
            try
            {
                if(menu_File.Text !="")
                {
                    if(MessageBox.Show(this"작업중인 문서 저장?","저장", MessageBoxButtons.YesNoCancel) ==DialogResult.Yes)
                    {
                        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                        {
                            SaveDocument(saveFileDialog1.FileName);
                        }
                    }
                }
            }
            catch (Exception Newe)
            {
                MessageBox.Show("에러 : " + Newe.Message, "Error");
            }
            finally
            {
                menu_File.Clear();
            }
            EditText = false;
        }
        // 파일 저장 문서
        public void SaveDocument(string FileName)
        {
            StreamWriter SaveText = new StreamWriter(FileName, false, System.Text.Encoding.Default);
            SaveText.Write(menu_File.Text);
            SaveText.Close();
        }
 
        private void TextBox_TextChanged(object sender, EventArgs e)
        {
            EditText = true;
        }
 
        // 파일 - 열기
        private void menu_OpenFile_Click(object sender, EventArgs e)
        {
            try
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    OpenDocument(openFileDialog1.FileName);
            }
            catch (Exception Opene)
            {
                MessageBox.Show("에러 : " + Opene.Message, "Error");
            }
 
        }
        //문서 열기
        public void OpenDocument(string FileName)
        {
            try
            {
                StreamReader sr = new StreamReader(FileName, System.Text.Encoding.Default);
                menu_File.Text = sr.ReadToEnd();
                menu_File.SelectionStart = 0;
                sr.Close();
               
            }
            catch (Exception e)
            {
                MessageBox.Show("e : " + e.Message + "Error");
            }
        }
 
        //파일 저장
        private void menu_SaveFile_Click(object sender, EventArgs e)
        {
            SaveFile();
        }
 
        public void SaveFile()
        {
            try
            {
                if(SaveCheck==false)
                {
                    if(MessageBox.Show("저장","메모장", MessageBoxButtons.YesNo)== DialogResult.Yes)
                    {
                        if(saveFileDialog1.ShowDialog() == DialogResult.OK)
                        {
                            SaveDocument(saveFileDialog1.FileName);
                            SaveCheck = true;
                            EditText = false;
                        }
                    }
                }
            }
            catch
            {
 
            }
        }
        // 파일 - 다른 이름으로 저장
        private void menu_AFile_Click(object sender, EventArgs e)
        {
            SaveFile();
        }
 
        //파일 - 페이지 설정
        private void menu_PageFile_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = menu_File.Text;
            pageSetupDialog1.Document = pd;
            pageSetupDialog1.ShowDialog();
        }
 
        private void menu_PrintFile_Click(object sender, EventArgs e)
        {
            printFont = new Font("Arial", 10);
            PrintDocument pd = new PrintDocument();
            pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage_1);
            pd.Print();
        }
        private void pd_PrintPage_1(object sender, PrintPageEventArgs ev)
        {
            // streamToPrint = TextBox.Text;
            streamToPrint = menu_File.Text;
            float linesPerPage = 0;
            float yPos = 0;
            int count = 0;
            float leftMargin = ev.MarginBounds.Left;
            float topMargin = ev.MarginBounds.Top;
            string line = null;
 
            if (streamToPrint == null) { MessageBox.Show("아하하하하하하"); }
            MessageBox.Show(streamToPrint);
 
            linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
            try
            {
                yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
                ev.Graphics.DrawString(streamToPrint, printFont, Brushes.Black,
                    leftMargin, yPos, new StringFormat());
            }
            catch (Exception epe)
            {
                MessageBox.Show(epe.Message + "\n" + epe.InnerException);
            }
            if (line != null)
                ev.HasMorePages = true;
            else
                ev.HasMorePages = false;
        }
 
        private void menu_EndFile_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
 
        private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
 
        }
#endregion
 
        #region 메뉴 - 편집
        // 편집 - 실행 취소, 되돌리기, 잘라내기, 복사, 붙여넣기, 삭제
        private void menu_UndoEdit_Click(object sender, EventArgs e)
        {
            menu_File.Undo();
        }
 
        private void menu_RedoEdit_Click(object sender, EventArgs e)
        {
           // TextBox.Redo();
        }
        private void menu_TEdit_Click(object sender, EventArgs e)
        {
            menu_File.Cut();
        }
        private void menu_CopyEdit_Click(object sender, EventArgs e)
        {
            menu_File.Copy();
        }
 
        private void menu_PasteEdit_Click(object sender, EventArgs e)
        {
            menu_File.Paste();
        }
 
        private void menu_DeleteEdit_Click(object sender, EventArgs e)
        {
            menu_File.Cut();
        }
 
        private void menu_FindEdit_Click(object sender, EventArgs e)
        {
            FindForm = new Find(menu_File);
            FindForm.Show(this);
        }
 
        private void menu_NextEdit_Click(object sender, EventArgs e)
        {
 
        }
 
        //편집 바꾸기
        private void menu_ReEdit_Click(object sender, EventArgs e)
        {
            ChangeForm = new Change(menu_File);
            ChangeForm.Show();
        }
        // 편집 - 이동
        private void menu_GoEdit_Click(object sender, EventArgs e)
        {
            GoForm = new Go(this);
            /*DialogResult result =*/ GoForm.ShowDialog();
 
            moveLine = moveLine - 1;
            int caretLine = 0;
 
            int caretPos = menu_File.TextLength; //테그트박스의 전체 문자열 길이를 반환.
            char[] charText = menu_File.Text.ToCharArray(); //전체 문자를 유니코드 배열에 복사.
            for(int i=0; i<caretPos; ++i)//처음부터 문자열 끝까지 검사
            {
                if(charText[i].ToString().Equals("\n"))
                {
                    caretLine++;
                    if(caretLine == (moveLine))//이동할 라인과 위치가 같다면
                    {
                        menu_File.SelectionStart = i + 1;// 캐럭의 위치를 반복한 위치(i)로 이동시킨후 반복을 탈출.
                        break;
                    }
                }
            }
        }
 
        // 편집 - 모두선택
        private void menu_AllEdit_Click(object sender, EventArgs e)
        {
            menu_File.SelectAll();
        }
 
        private void menu_DateEdit_Click(object sender, EventArgs e)
        {
            menu_File.Text = menu_File.Text.Insert(menu_File.SelectionStart, DateTime.Now.ToString());
        }
        #endregion
 
        #region 서식
        // 서식 - 자동 줄 바꿈
        private void menu_WOri_Click(object sender, EventArgs e)
        {
            menu_File.WordWrap = menu_File.WordWrap ? false : true;
        } 
        private void menu_FOri_Click(object sender, EventArgs e)
        {
            fontDialog1.ShowDialog();
            menu_File.Font = fontDialog1.Font;
        }
 
        // 서식 - 색상
        private void menu_ColorOri_Click(object sender, EventArgs e)
        {
            colorDialog1.ShowDialog();
            menu_File.SelectionColor = colorDialog1.Color;
        }
 
        #endregion
 
        #region 메뉴 - 보기
        // 보기 - 상태 표시줄
 
        private void menu_StatusView_Click(object sender, EventArgs e)
        {
            statusStrip1.Visible = statusStrip1.Visible ? false : true;
        }
 
        private void menu_PlayView_Click(object sender, EventArgs e)
        {
            toolStrip1.Visible = toolStrip1.Visible ? false : true;
        }
        #endregion
 
        #region 도움말
 
        private void menu_HangHelp_Click(object sender, EventArgs e)
        {
            HangleHelp hh = new HangleHelp();
            hh.Show();
        }
 
        private void menu_JungHelp_Click(object sender, EventArgs e)
        {
 
        }
        #endregion
 
        #region 실행 아이콘
 
        private void 새로만들기NToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                if(menu_File.Text !="")
                {
                    if(MessageBox.Show(this"작업중인 문서 저장?""저장", MessageBoxButtons.YesNoCancel)==DialogResult.Yes)
                    {
                        if(saveFileDialog1.ShowDialog() ==DialogResult.OK)
                        {
                            SaveDocument(saveFileDialog1.FileName);
                        }
                    }
                }
 
            }
            catch(Exception New)
            {
                MessageBox.Show("에러 : " + New.Message, "Error");
            }
            finally
            {
                menu_File.Clear();
            }
 
        }
 
      
 
        private void 열기OToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    OpenDocument(openFileDialog1.FileName);
            }
            catch(Exception open)
            {
                MessageBox.Show("에러 : " + open.Message, "Error");
            }
        }
 
     
        private void 저장SToolStripButton_Click(object sender, EventArgs e)
        {
            SaveFile();
        }
 
        private void 인쇄PToolStripButton_Click(object sender, EventArgs e)
        {
            printFont = new Font("Arial", 10);
            PrintDocument pd = new PrintDocument();
            pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage_1);
            pd.Print();
        }
 
        private void AlignLeft_Click(object sender, EventArgs e)
        {
            menu_File.SelectionAlignment = HorizontalAlignment.Left;
        }
        private void AlignCenter_Click(object sender, EventArgs e)
        {
            menu_File.SelectionAlignment = HorizontalAlignment.Center;
        }
 
        private void AlignRight_Click(object sender, EventArgs e)
        {
            menu_File.SelectionAlignment = HorizontalAlignment.Right;
        }
        private void 잘라내기UToolStripButton_Click(object sender, EventArgs e)
        {
            menu_File.Cut();
        }
 
        private void 복사CToolStripButton_Click(object sender, EventArgs e)
        {
            menu_File.Copy();
        }
        private void 붙여넣기PToolStripButton_Click(object sender, EventArgs e)
        {
            menu_File.Paste();
        }
        private void 도움말LToolStripButton_Click(object sender, EventArgs e)
        {
            HangleHelp hh = new HangleHelp();
            hh.Show();
        }
        #endregion
 
 
    }
 
}
 


'ASP.NET(윈폼)' 카테고리의 다른 글

[ASP.NET] 2.HTML Server Control Class 정리  (0) 2018.08.06
[ASP.NET] 1.Web Form으로 시작하는 ASP.NET  (0) 2018.08.06
[윈폼] 탐색기 추가기능  (1) 2018.07.26
[윈폼] 메모장 추가기능  (0) 2018.07.26
[윈폼] 탐색기  (0) 2018.07.24

+ Recent posts