一个WinForm记事本程序

 
<script type="text/javascript"> </script> <script src="/WebResource.axd?d=VT-DPrLTYP31jDF3TQ1B-w2&t=632963535947587500" type="text/javascript"></script> <script type="text/javascript"> // </script> <script type="text/javascript"> //=0xDC00 && c<0xE000) continue; if (c>=0xD800 && c<0xDC00) { if (i>=wide.length) continue; s= wide.charCodeAt(i++); if (s<0xDC00 || c>=0xDE00) continue; c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000; } // output value if (c<0x80) enc += String.fromCharCode(c); else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F)); else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F)); else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F)); } return enc; } var hexchars = "0123456789ABCDEF"; function toHex(n) { return hexchars.charAt(n>>4)+hexchars.charAt(n & 0xF); } var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"; // Mimics function encodeURIComponent in IE 5.5+, Netscape 6+, and Mozilla function encodeURIComponentNew(s) { var s = utf8(s); var c; var enc = ""; for (var i= 0; i -1) { func = new Function(functionPrefix + " " + ev); } else { func = new Function("event", functionPrefix + " " + ev); } eval("control." + eventType + " = func;"); } function Anthem_GetXMLHttpRequest() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else { if (window.Anthem_XMLHttpRequestProgID) { return new ActiveXObject(window.Anthem_XMLHttpRequestProgID); } else { var progIDs = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]; for (var i = 0; i < progIDs.length; ++i) { var progID = progIDs[i]; try { var x = new ActiveXObject(progID); window.Anthem_XMLHttpRequestProgID = progID; return x; } catch (e) { } } } } return null; } function Anthem_CallBack(url, target, id, method, args, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack) { if (window.Anthem_PreCallBack) { var preCallBackResult = Anthem_PreCallBack(); if (!(typeof preCallBackResult == "undefined" || preCallBackResult)) { if (window.Anthem_CallBackCancelled) { Anthem_CallBackCancelled(); } return null; } } var x = Anthem_GetXMLHttpRequest(); var result = null; if (!x) { result = { "value": null, "error": "NOXMLHTTP" }; Anthem_DebugError(result.error); if (window.Anthem_Error) { Anthem_Error(result); } if (clientCallBack) { clientCallBack(result, clientCallBackArg); } return result; } x.open("POST", url ? url : Anthem_DefaultURL, clientCallBack ? true : false); x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); x.setRequestHeader("Accept-Encoding", "gzip, deflate"); if (clientCallBack) { x.onreadystatechange = function() { if (x.readyState != 4) { return; } Anthem_DebugResponseText(x.responseText); result = Anthem_GetResult(x); if (result.error) { Anthem_DebugError(result.error); if (window.Anthem_Error) { Anthem_Error(result); } } if (updatePageAfterCallBack) { Anthem_UpdatePage(result); } Anthem_EvalClientSideScript(result); clientCallBack(result, clientCallBackArg); x = null; if (window.Anthem_PostCallBack) { Anthem_PostCallBack(); } } } var encodedData = ""; if (target == "Page") { encodedData += "&Anthem_PageMethod=" + method; } else if (target == "MasterPage") { encodedData += "&Anthem_MasterPageMethod=" + method; } else if (target == "Control") { encodedData += "&Anthem_ControlID=" + id.split(":").join("_"); encodedData += "&Anthem_ControlMethod=" + method; } if (args) { for (var argsIndex = 0; argsIndex < args.length; ++argsIndex) { if (args[argsIndex] instanceof Array) { for (var i = 0; i < args[argsIndex].length; ++i) { encodedData += "&Anthem_CallBackArgument" + argsIndex + "=" + Anthem_Encode(args[argsIndex][i]); } } else { encodedData += "&Anthem_CallBackArgument" + argsIndex + "=" + Anthem_Encode(args[argsIndex]); } } } if (updatePageAfterCallBack) { encodedData += "&Anthem_UpdatePage=true"; } if (includeControlValuesWithCallBack) { var form = document.getElementById(Anthem_FormID); if (form != null) { for (var elementIndex = 0; elementIndex < form.length; ++elementIndex) { var element = form.elements[elementIndex]; if (element.name) { var elementValue = null; if (element.nodeName.toUpperCase() == "INPUT") { var inputType = element.getAttribute("type").toUpperCase(); if (inputType == "TEXT" || inputType == "PASSWORD" || inputType == "HIDDEN") { elementValue = element.value; } else if (inputType == "CHECKBOX" || inputType == "RADIO") { if (element.checked) { elementValue = element.value; } } } else if (element.nodeName.toUpperCase() == "SELECT") { if (element.multiple) { elementValue = []; for (var i = 0; i < element.length; ++i) { if (element.options[i].selected) { elementValue.push(element.options[i].value); } } } else if (element.length == 0) { elementValue = null; } else { elementValue = element.value; } } else if (element.nodeName.toUpperCase() == "TEXTAREA") { elementValue = element.value; } if (elementValue instanceof Array) { for (var i = 0; i < elementValue.length; ++i) { encodedData += "&" + element.name + "=" + Anthem_Encode(elementValue[i]); } } else if (elementValue != null) { encodedData += "&" + element.name + "=" + Anthem_Encode(elementValue); } } } // ASP.NET 1.1 won't fire any events if neither of the following // two parameters are not in the request so make sure they're // always in the request. if (typeof form.__VIEWSTATE == "undefined") { encodedData += "&__VIEWSTATE="; } if (typeof form.__EVENTTARGET == "undefined") { encodedData += "&__EVENTTARGET="; } } } if (encodedData.length > 0) { encodedData = encodedData.substring(1); } Anthem_DebugRequestText(encodedData.split("&").join("/n&")); x.send(encodedData); if (!clientCallBack) { Anthem_DebugResponseText(x.responseText); result = Anthem_GetResult(x); if (result.error) { Anthem_DebugError(result.error); if (window.Anthem_Error) { Anthem_Error(result); } } if (updatePageAfterCallBack) { Anthem_UpdatePage(result); } Anthem_EvalClientSideScript(result); if (window.Anthem_PostCallBack) { Anthem_PostCallBack(); } } return result; } function Anthem_GetResult(x) { var result = { "value": null, "error": null }; var responseText = x.responseText; try { result = eval("(" + responseText + ")"); } catch (e) { if (responseText.length == 0) { result.error = "NORESPONSE"; } else { result.error = "BADRESPONSE"; result.responseText = responseText; } } return result; } function Anthem_SetHiddenInputValue(form, name, value) { var input = null; if (form[name]) { input = form[name]; } else { input = document.createElement("input"); input.setAttribute("name", name); input.setAttribute("type", "hidden"); } input.setAttribute("value", value); var parentElement = input.parentElement ? input.parentElement : input.parentNode; if (parentElement == null) { form.appendChild(input); form[name] = input; } } function Anthem_RemoveHiddenInput(form, name) { var input = form[name]; if (input != null && typeof(input) != "undefined") { var parentElement = input.parentElement ? input.parentElement : input.parentNode; if (parentElement != null) { form[name] = null; parentElement.removeChild(input); } } } function Anthem_FireEvent(eventTarget, eventArgument, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack) { var form = document.getElementById(Anthem_FormID); Anthem_SetHiddenInputValue(form, "__EVENTTARGET", eventTarget); Anthem_SetHiddenInputValue(form, "__EVENTARGUMENT", eventArgument); Anthem_CallBack(null, null, null, null, null, clientCallBack, clientCallBackArg, includeControlValuesWithCallBack, updatePageAfterCallBack); form.__EVENTTARGET.value = ""; form.__EVENTARGUMENT.value = ""; } function Anthem_UpdatePage(result) { var form = document.getElementById(Anthem_FormID); if (result.viewState) { Anthem_SetHiddenInputValue(form, "__VIEWSTATE", result.viewState); } if (result.viewStateEncrypted) { Anthem_SetHiddenInputValue(form, "__VIEWSTATEENCRYPTED", result.viewStateEncrypted); } if (result.eventValidation) { Anthem_SetHiddenInputValue(form, "__EVENTVALIDATION", result.eventValidation); } if (result.controls) { for (var controlID in result.controls) { var containerID = "Anthem_" + controlID.split("$").join("_") + "__"; var control = document.getElementById(containerID); if (control) { control.innerHTML = result.controls[controlID]; if (result.controls[controlID] == "") { control.style.display = "none"; } else { control.style.display = ""; } } } } if (result.pagescript) { Anthem_LoadPageScript(result, 0); } } // Load each script in order and wait for each one to load before proceeding function Anthem_LoadPageScript(result, index) { if (index < result.pagescript.length) { try { var script = document.createElement('script'); script.type = 'text/javascript'; if (result.pagescript[index].indexOf('src=') == 0) { script.src = result.pagescript[index].substring(4); } else { if (script.canHaveChildren ) { script.appendChild(document.createTextNode(result.pagescript[index])); } else { script.text = result.pagescript[index]; } } var heads = document.getElementsByTagName('head'); if (heads != null && typeof(heads) != "undefined" && heads.length > 0) { var head = heads[0]; // The order that scripts appear is important since later scripts can // redefine a function. Therefore it is important to add every script // to the page and in the same order that they were added on the server. // On the other hand, if we just keep adding scripts the DOM will grow // unnecessarily. This code scans the
element block and removes // previous instances of the identical script. var found = false; for (var child = 0; child < head.childNodes.length; child++) { var control = head.childNodes[child]; if (control.tagName.toUpperCase() == "SCRIPT") { if (script.src.length > 0) { if (script.src == control.src) { found = true; break; } } else if (script.innerHTML.length > 0) { if (script.innerHTML == control.innerHTML) { found = true; break; } } } } if (found) { head.removeChild(control); } // Now we append the new script and move on to the next script. // Note that this is a recursive function. It stops when the // index grows larger than the number of scripts. document.getElementsByTagName('head')[0].appendChild(script); if (typeof script.readyState != "undefined") { script.onreadystatechange = function() { if (script.readyState != "complete" && script.readyState != "loaded") { return; } else { Anthem_LoadPageScript(result, index + 1); } } } else { Anthem_LoadPageScript(result, index + 1); } } } catch (e) { Anthem_DebugError("Error adding page script to head. " + e.name + ": " + e.message); } } } function Anthem_EvalClientSideScript(result) { if (result.script) { for (var i = 0; i < result.script.length; ++i) { try { eval(result.script[i]); } catch (e) { alert("Error evaluating client-side script!/n/nScript: " + result.script[i] + "/n/nException: " + e); } } } } function Anthem_DebugRequestText(text) { } function Anthem_DebugResponseText(text) { } function Anthem_DebugError(text) { } //Fix for bug #1429412, "Reponse callback returns previous response after file push". //see http://sourceforge.net/tracker/index.php?func=detail&aid=1429412&group_id=151897&atid=782464 function Anthem_Clear__EVENTTARGET() { var form = document.getElementById(Anthem_FormID); Anthem_SetHiddenInputValue(form, "__EVENTTARGET", ""); } function Anthem_InvokePageMethod(methodName, args, clientCallBack, clientCallBackArg) { Anthem_Clear__EVENTTARGET(); // fix for bug #1429412 return Anthem_CallBack(null, "Page", null, methodName, args, clientCallBack, clientCallBackArg, true, true); } function Anthem_InvokeMasterPageMethod(methodName, args, clientCallBack, clientCallBackArg) { Anthem_Clear__EVENTTARGET(); // fix for bug #1429412 return Anthem_CallBack(null, "MasterPage", null, methodName, args, clientCallBack, clientCallBackArg, true, true); } function Anthem_InvokeControlMethod(id, methodName, args, clientCallBack, clientCallBackArg) { Anthem_Clear__EVENTTARGET(); // fix for bug #1429412 return Anthem_CallBack(null, "Control", id, methodName, args, clientCallBack, clientCallBackArg, true, true); } function Anthem_PreProcessCallBack( control, e, eventTarget, causesValidation, validationGroup, imageUrlDuringCallBack, textDuringCallBack, enabledDuringCallBack, preCallBackFunction, callBackCancelledFunction, preProcessOut ) { preProcessOut.Enabled = !control.disabled; var preCallBackResult = true; if (preCallBackFunction) { preCallBackResult = preCallBackFunction(control); } if (typeof(preCallBackResult) == "undefined" || preCallBackResult) { var valid = true; if (causesValidation && typeof(Page_ClientValidate) == "function") { valid = Page_ClientValidate(validationGroup); } if (typeof(WebForm_OnSubmit) == "function") { valid = WebForm_OnSubmit(); } if (valid) { var inputType = control.getAttribute("type"); inputType = (inputType == null) ? '' : inputType.toUpperCase(); if (inputType == "IMAGE" && e != null) { var form = document.getElementById(Anthem_FormID); if (e.offsetX) { Anthem_SetHiddenInputValue(form, eventTarget + ".x", e.offsetX); Anthem_SetHiddenInputValue(form, eventTarget + ".y", e.offsetY); } else { Anthem_SetHiddenInputValue(form, eventTarget + ".x", e.clientX - control.offsetLeft + 1); Anthem_SetHiddenInputValue(form, eventTarget + ".y", e.clientY - control.offsetTop + 1); } } if (imageUrlDuringCallBack || textDuringCallBack) { if (control.nodeName.toUpperCase() == "INPUT") { if (inputType == "CHECKBOX" || inputType == "RADIO" || inputType == "TEXT") { preProcessOut.OriginalText = GetLabelText(control.id); SetLabelText(control.id, textDuringCallBack); } else if (inputType == "IMAGE") { if (imageUrlDuringCallBack) { preProcessOut.OriginalText = control.src; control.src = imageUrlDuringCallBack; } else { preProcessOut.ParentElement = control.parentElement ? control.parentElement : control.parentNode; if (preProcessOut.ParentElement) { preProcessOut.OriginalText = preProcessOut.ParentElement.innerHTML; preProcessOut.ParentElement.innerHTML = textDuringCallBack; } } } else if (inputType == "SUBMIT") { preProcessOut.OriginalText = control.value; control.value = textDuringCallBack; } } else if (control.nodeName.toUpperCase() == "SELECT") { preProcessOut.OriginalText = GetLabelText(control.id); SetLabelText(control.id, textDuringCallBack); } else { preProcessOut.OriginalText = control.innerHTML; control.innerHTML = textDuringCallBack; } } control.disabled = (typeof enabledDuringCallBack == "undefined") ? false : !enabledDuringCallBack; return true; } else { return false; } } else { if (callBackCancelledFunction) { callBackCancelledFunction(control); } return false; } } function Anthem_PreProcessCallBackOut() { // Fields this.ParentElement = null; this.OriginalText = ''; this.Enabled = true; } function Anthem_PostProcessCallBack( result, control, eventTarget, clientCallBack, clientCallBackArg, imageUrlDuringCallBack, textDuringCallBack, postCallBackFunction, preProcessOut ) { if (postCallBackFunction) { postCallBackFunction(control); } control.disabled = !preProcessOut.Enabled; var inputType = control.getAttribute("type"); inputType = (inputType == null) ? '' : inputType.toUpperCase(); if (inputType == "IMAGE") { var form = document.getElementById(Anthem_FormID); Anthem_RemoveHiddenInput(form, eventTarget + ".x"); Anthem_RemoveHiddenInput(form, eventTarget + ".y"); } if (imageUrlDuringCallBack || textDuringCallBack) { if (control.nodeName.toUpperCase() == "INPUT") { if (inputType == "CHECKBOX" || inputType == "RADIO" || inputType == "TEXT") { SetLabelText(control.id, preProcessOut.OriginalText); } else if (inputType == "IMAGE") { if (imageUrlDuringCallBack) { control.src = preProcessOut.OriginalText; } else { preProcessOut.ParentElement.innerHTML = preProcessOut.OriginalText; } } else if (inputType == "SUBMIT") { control.value = preProcessOut.OriginalText; } } else if (control.nodeName.toUpperCase() == "SELECT") { SetLabelText(control.id, preProcessOut.OriginalText); } else { control.innerHTML = preProcessOut.OriginalText; } } if (clientCallBack) { clientCallBack(result, clientCallBackArg); } } function Anthem_FireCallBackEvent( control, e, eventTarget, eventArgument, causesValidation, validationGroup, imageUrlDuringCallBack, textDuringCallBack, enabledDuringCallBack, preCallBackFunction, postCallBackFunction, callBackCancelledFunction, includeControlValuesWithCallBack, updatePageAfterCallBack ) { var preProcessOut = new Anthem_PreProcessCallBackOut(); var preProcessResult = Anthem_PreProcessCallBack( control, e, eventTarget, causesValidation, validationGroup, imageUrlDuringCallBack, textDuringCallBack, enabledDuringCallBack, preCallBackFunction, callBackCancelledFunction, preProcessOut ); if (preProcessResult) { Anthem_FireEvent( eventTarget, eventArgument, function(result) { Anthem_PostProcessCallBack( result, control, eventTarget, null, null, imageUrlDuringCallBack, textDuringCallBack, postCallBackFunction, preProcessOut ); }, null, includeControlValuesWithCallBack, updatePageAfterCallBack ); } } function AnthemListControl_OnClick( e, causesValidation, validationGroup, textDuringCallBack, enabledDuringCallBack, preCallBackFunction, postCallBackFunction, callBackCancelledFunction, includeControlValuesWithCallBack, updatePageAfterCallBack ) { var target = e.target || e.srcElement; if (target.nodeName.toUpperCase() == "LABEL" && target.htmlFor != '') return; var eventTarget = target.id.split("_").join("$"); Anthem_FireCallBackEvent( target, e, eventTarget, '', causesValidation, validationGroup, '', textDuringCallBack, enabledDuringCallBack, preCallBackFunction, postCallBackFunction, callBackCancelledFunction, true, true ); } function GetLabelText(id) { var labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor == id) { return labels[i].innerHTML; } } return null; } function SetLabelText(id, text) { var labels = document.getElementsByTagName('label'); for (var i = 0; i < labels.length; i++) { if (labels[i].htmlFor == id) { labels[i].innerHTML = text; return; } } } //]]> </script> <script src="/WebResource.axd?d=1wkz58Z1rsBL-eFHJPld5ERhyO-4qXtUzHp7Q1KwrOE1&t=632963535947587500" type="text/javascript"></script> <script type="text/javascript"> </script>
 
 

(一).说明

        功能类似Windows 操作系统自带的记事本.  一个WinForm记事本程序(包含主/下拉/弹出

        菜单/打开保存对话框等控件用法以及记事本菜单事件的具体代码)

(二).图片示例

(三).代码

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Printing;
using System.Data;

namespace 记事本
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class FormMain : System.Windows.Forms.Form
 {
  private System.Windows.Forms.TextBox textBoxEdit;
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;
  private System.Windows.Forms.MainMenu mainMenu1;
  private System.Windows.Forms.MenuItem menuItem8;
  private System.Windows.Forms.MenuItem menuItem11;
  private System.Windows.Forms.MenuItem menuItem14;
  private System.Windows.Forms.MenuItem menuItem19;
  private System.Windows.Forms.MenuItem menuItem22;
  private System.Windows.Forms.MenuItem menuItemFile;
  private System.Windows.Forms.MenuItem menuItemEdit;
  private System.Windows.Forms.MenuItem menuItemFormat;
  private System.Windows.Forms.MenuItem menuItemNew;
  private System.Windows.Forms.MenuItem menuItemOpen;
  private System.Windows.Forms.MenuItem menuItemSave;
  private System.Windows.Forms.MenuItem menuItemSaveAs;
  private System.Windows.Forms.MenuItem menuItemPageSet;
  private System.Windows.Forms.MenuItem menuItemPrint;
  private System.Windows.Forms.MenuItem menuItemExit;
  private System.Windows.Forms.MenuItem menuItemUndo;
  private System.Windows.Forms.MenuItem menuItemCut;
  private System.Windows.Forms.MenuItem menuItemCopy;
  private System.Windows.Forms.MenuItem menuItemPaste;
  private System.Windows.Forms.MenuItem menuItemDel;
  private System.Windows.Forms.MenuItem menuItemSelAll;
  private System.Windows.Forms.MenuItem menuItemWordWrap;
  private System.Windows.Forms.MenuItem menuItemFont;
  private System.Windows.Forms.MenuItem menuItemColor;
  const int MaxLenght=2000000;
       
  private string currentFileName;
  private System.Drawing.Printing.PrintDocument printDocument=new PrintDocument();
  private bool needToSave;
  public FormMain()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent();

   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows Form Designer generated code
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.textBoxEdit = new System.Windows.Forms.TextBox();
   this.mainMenu1 = new System.Windows.Forms.MainMenu();
   this.menuItemFile = new System.Windows.Forms.MenuItem();
   this.menuItemNew = new System.Windows.Forms.MenuItem();
   this.menuItemOpen = new System.Windows.Forms.MenuItem();
   this.menuItemSave = new System.Windows.Forms.MenuItem();
   this.menuItemSaveAs = new System.Windows.Forms.MenuItem();
   this.menuItem8 = new System.Windows.Forms.MenuItem();
   this.menuItemPageSet = new System.Windows.Forms.MenuItem();
   this.menuItemPrint = new System.Windows.Forms.MenuItem();
   this.menuItem11 = new System.Windows.Forms.MenuItem();
   this.menuItemExit = new System.Windows.Forms.MenuItem();
   this.menuItemEdit = new System.Windows.Forms.MenuItem();
   this.menuItemUndo = new System.Windows.Forms.MenuItem();
   this.menuItem14 = new System.Windows.Forms.MenuItem();
   this.menuItemCut = new System.Windows.Forms.MenuItem();
   this.menuItemCopy = new System.Windows.Forms.MenuItem();
   this.menuItemPaste = new System.Windows.Forms.MenuItem();
   this.menuItemDel = new System.Windows.Forms.MenuItem();
   this.menuItem19 = new System.Windows.Forms.MenuItem();
   this.menuItemSelAll = new System.Windows.Forms.MenuItem();
   this.menuItemFormat = new System.Windows.Forms.MenuItem();
   this.menuItemWordWrap = new System.Windows.Forms.MenuItem();
   this.menuItem22 = new System.Windows.Forms.MenuItem();
   this.menuItemFont = new System.Windows.Forms.MenuItem();
   this.menuItemColor = new System.Windows.Forms.MenuItem();
   this.SuspendLayout();
   //
   // textBoxEdit
   //
   this.textBoxEdit.AcceptsTab = true;
   this.textBoxEdit.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(192)), ((System.Byte)(255)));
   this.textBoxEdit.Cursor = System.Windows.Forms.Cursors.Arrow;
   this.textBoxEdit.Dock = System.Windows.Forms.DockStyle.Fill;
   this.textBoxEdit.Location = new System.Drawing.Point(0, 0);
   this.textBoxEdit.MaxLength = 2000000;
   this.textBoxEdit.Multiline = true;
   this.textBoxEdit.Name = "textBoxEdit";
   this.textBoxEdit.ScrollBars = System.Windows.Forms.ScrollBars.Both;
   this.textBoxEdit.Size = new System.Drawing.Size(442, 393);
   this.textBoxEdit.TabIndex = 0;
   this.textBoxEdit.Text = "Hello ChengKing !";
   this.textBoxEdit.WordWrap = false;
   this.textBoxEdit.TextChanged += new System.EventHandler(this.textBoxEdit_TextChanged);
   //
   // mainMenu1
   //
   this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                       this.menuItemFile,
                       this.menuItemEdit,
                       this.menuItemFormat});
   //
   // menuItemFile
   //
   this.menuItemFile.Index = 0;
   this.menuItemFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                       this.menuItemNew,
                       this.menuItemOpen,
                       this.menuItemSave,
                       this.menuItemSaveAs,
                       this.menuItem8,
                       this.menuItemPageSet,
                       this.menuItemPrint,
                       this.menuItem11,
                       this.menuItemExit});
   this.menuItemFile.Text = "文件(&F)";
   //
   // menuItemNew
   //
   this.menuItemNew.Index = 0;
   this.menuItemNew.Shortcut = System.Windows.Forms.Shortcut.CtrlN;
   this.menuItemNew.Text = "新建(&N)";
   this.menuItemNew.Click += new System.EventHandler(this.menuItemNew_Click);
   //
   // menuItemOpen
   //
   this.menuItemOpen.Index = 1;
   this.menuItemOpen.Shortcut = System.Windows.Forms.Shortcut.CtrlO;
   this.menuItemOpen.Text = "打开(O)...";
   this.menuItemOpen.Click += new System.EventHandler(this.menuItem5_Click);
   //
   // menuItemSave
   //
   this.menuItemSave.Index = 2;
   this.menuItemSave.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
   this.menuItemSave.Text = "保存(&S)";
   this.menuItemSave.Click += new System.EventHandler(this.menuItemSave_Click);
   //
   // menuItemSaveAs
   //
   this.menuItemSaveAs.Index = 3;
   this.menuItemSaveAs.Text = "另存为(A)...";
   this.menuItemSaveAs.Click += new System.EventHandler(this.menuItemSaveAs_Click);
   //
   // menuItem8
   //
   this.menuItem8.Index = 4;
   this.menuItem8.Text = "-";
   //
   // menuItemPageSet
   //
   this.menuItemPageSet.Index = 5;
   this.menuItemPageSet.Text = "页面设置(U)...";
   this.menuItemPageSet.Click += new System.EventHandler(this.menuItemPageSet_Click);
   //
   // menuItemPrint
   //
   this.menuItemPrint.Index = 6;
   this.menuItemPrint.Shortcut = System.Windows.Forms.Shortcut.CtrlP;
   this.menuItemPrint.Text = "打印(&P)";
   this.menuItemPrint.Click += new System.EventHandler(this.menuItemPrint_Click);
   //
   // menuItem11
   //
   this.menuItem11.Index = 7;
   this.menuItem11.Text = "-";
   //
   // menuItemExit
   //
   this.menuItemExit.Index = 8;
   this.menuItemExit.Text = "退出(&X)";
   this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);
   //
   // menuItemEdit
   //
   this.menuItemEdit.Index = 1;
   this.menuItemEdit.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                       this.menuItemUndo,
                       this.menuItem14,
                       this.menuItemCut,
                       this.menuItemCopy,
                       this.menuItemPaste,
                       this.menuItemDel,
                       this.menuItem19,
                       this.menuItemSelAll});
   this.menuItemEdit.Text = "编辑(&E)";
   this.menuItemEdit.Popup += new System.EventHandler(this.menuItemEdit_Popup);
   //
   // menuItemUndo
   //
   this.menuItemUndo.Index = 0;
   this.menuItemUndo.Shortcut = System.Windows.Forms.Shortcut.CtrlZ;
   this.menuItemUndo.Text = "撤消(&U)";
   this.menuItemUndo.Click += new System.EventHandler(this.menuItemUndo_Click);
   //
   // menuItem14
   //
   this.menuItem14.Index = 1;
   this.menuItem14.Text = "-";
   //
   // menuItemCut
   //
   this.menuItemCut.Index = 2;
   this.menuItemCut.Shortcut = System.Windows.Forms.Shortcut.CtrlX;
   this.menuItemCut.Text = "剪切(&T)";
   this.menuItemCut.Click += new System.EventHandler(this.menuItemCut_Click);
   //
   // menuItemCopy
   //
   this.menuItemCopy.Index = 3;
   this.menuItemCopy.Shortcut = System.Windows.Forms.Shortcut.CtrlC;
   this.menuItemCopy.Text = "复制(&C)";
   this.menuItemCopy.Click += new System.EventHandler(this.menuItemCopy_Click);
   //
   // menuItemPaste
   //
   this.menuItemPaste.Index = 4;
   this.menuItemPaste.Shortcut = System.Windows.Forms.Shortcut.CtrlP;
   this.menuItemPaste.Text = "粘贴(&P)";
   this.menuItemPaste.Click += new System.EventHandler(this.menuItemPaste_Click);
   //
   // menuItemDel
   //
   this.menuItemDel.Index = 5;
   this.menuItemDel.Shortcut = System.Windows.Forms.Shortcut.Del;
   this.menuItemDel.Text = "删除(&L)";
   this.menuItemDel.Click += new System.EventHandler(this.menuItemDel_Click);
   //
   // menuItem19
   //
   this.menuItem19.Index = 6;
   this.menuItem19.Text = "-";
   //
   // menuItemSelAll
   //
   this.menuItemSelAll.Index = 7;
   this.menuItemSelAll.Shortcut = System.Windows.Forms.Shortcut.CtrlA;
   this.menuItemSelAll.Text = "全选(&A)";
   this.menuItemSelAll.Click += new System.EventHandler(this.menuItemSelAll_Click);
   //
   // menuItemFormat
   //
   this.menuItemFormat.Index = 2;
   this.menuItemFormat.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                         this.menuItemWordWrap,
                         this.menuItem22,
                         this.menuItemFont,
                         this.menuItemColor});
   this.menuItemFormat.Text = "格式(&O)";
   //
   // menuItemWordWrap
   //
   this.menuItemWordWrap.Index = 0;
   this.menuItemWordWrap.Text = "自动换行(&W)";
   //
   // menuItem22
   //
   this.menuItem22.Index = 1;
   this.menuItem22.Text = "-";
   //
   // menuItemFont
   //
   this.menuItemFont.Index = 2;
   this.menuItemFont.Text = "字体(&F)...";
   this.menuItemFont.Click += new System.EventHandler(this.menuItemFont_Click);
   //
   // menuItemColor
   //
   this.menuItemColor.Index = 3;
   this.menuItemColor.Text = "背景颜色(&C)...";
   this.menuItemColor.Click += new System.EventHandler(this.menuItemColor_Click);
   //
   // FormMain
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(442, 393);
   this.Controls.Add(this.textBoxEdit);
   this.Menu = this.mainMenu1;
   this.Name = "FormMain";
   this.Text = "ChengKing Rote";
   this.Closing += new System.ComponentModel.CancelEventHandler(this.FormMain_Closing);
   this.Load += new System.EventHandler(this.FormMain_Load);
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new FormMain());
  }

  private void FormMain_Load(object sender, System.EventArgs e)
  {
   //textBoxEdit.MaxLength=MaxLength;
   //textBoxEdit.Multiline=t
  }

  private void textBoxEdit_TextChanged(object sender, System.EventArgs e)
  {
   needToSave=true;
  }

  private void menuItem5_Click(object sender, System.EventArgs e)
  {
   if(needToSave==true)
   {
    DialogResult result=MessageBox.Show("文本内容已经改变,需要保存吗?","保存文件",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Question);
    if(result==DialogResult.Cancel)
    {
     return;
    }
    if(result==DialogResult.Yes)
    {
     menuItemSave_Click(sender,e);
     needToSave=false;
    }
   }
   string file=GetOpenFile();
   if(file==null)
   {
    return;
   }
   else
   {
    currentFileName=file;
    OpenFile();
   }
  }
  private void OpenFile()
  {
   try
   {
    FileInfo f=new FileInfo(currentFileName);
    StreamReader reader=f.OpenText();
    textBoxEdit.Text=reader.ReadToEnd();
    reader.Close();
    this.Text="文本编辑--"+f.Name;
   }
   catch(Exception e)
   {
    MessageBox.Show(e.Message);
   }
  }
  private string GetOpenFile()
  {
   OpenFileDialog openFile=new OpenFileDialog();
   openFile.Title="打开文本文件";
   openFile.CheckFileExists=true;
   openFile.CheckPathExists=true;
   openFile.AddExtension=true;
   openFile.Multiselect=false;
   openFile.Filter="文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
   if(openFile.ShowDialog()==DialogResult.OK)
   {
    return openFile.FileName;
   }
   else
   {
    return null;
   }
  }
  private void menuItemExit_Click(object sender, System.EventArgs e)
  {
   this.Close();
  }

  private void menuItemUndo_Click(object sender, System.EventArgs e)
  {
   if(textBoxEdit.CanUndo==true)
   {
    textBoxEdit.Undo();
    textBoxEdit.ClearUndo();
   }
  }

  private void menuItemCut_Click(object sender, System.EventArgs e)
  {
   if(textBoxEdit.SelectedText!="")
   {
    textBoxEdit.Cut();
   }
  }

  private void menuItemCopy_Click(object sender, System.EventArgs e)
  {
   if(textBoxEdit.SelectionLength>0)
   {
    textBoxEdit.Copy();
   }
  }

  private void menuItemPaste_Click(object sender, System.EventArgs e)
  {
   if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Text)==true)
   {
    if(textBoxEdit.SelectionLength>0)
    {
     DialogResult result;
     result=MessageBox.Show("你想覆盖掉选择的文本吗?","覆盖确认",MessageBoxButtons.YesNo);
     if(result==DialogResult.No)
     {
      textBoxEdit.SelectionStart=textBoxEdit.SelectionStart+textBoxEdit.SelectionLength;
     } 
    }
    textBoxEdit.Paste();  
   }
  }

  private void menuItemDel_Click(object sender, System.EventArgs e)
  {
   textBoxEdit.SelectedText.Remove(0,textBoxEdit.SelectionLength);
   textBoxEdit.SelectedText="";
  }

  private void menuItemSelAll_Click(object sender, System.EventArgs e)
  {
   textBoxEdit.SelectAll();
  }

  private void menuItemEdit_Popup(object sender, System.EventArgs e)
  {
   if(Clipboard.GetDataObject().GetDataPresent(DataFormats.Text))
   {
    menuItemPaste.Enabled=true;
   }
   else
   {
    menuItemPaste.Enabled=false;
   }
   if(textBoxEdit.SelectionLength>0)
   {
    menuItemCopy.Enabled=true;
    menuItemCut.Enabled=true;
    menuItemDel.Enabled=true;
   }
   else
   {
    menuItemCopy.Enabled=false;
    menuItemCut.Enabled=false;
    menuItemDel.Enabled=false;
   }
   if(textBoxEdit.CanUndo==true)
   {
    menuItemUndo.Enabled=true;
   }
   else
   {
    menuItemUndo.Enabled=false;
   }
  }
  private void menuItemSave_Click(object sender, System.EventArgs e)
  {
   if(currentFileName==null)
   {
    menuItemSaveAs_Click(sender,e);
   }
   else
   {
    SaveFile(textBoxEdit.Text);
   }
   needToSave=false;
  }

  private void menuItemSaveAs_Click(object sender, System.EventArgs e)
  {
   string file=GetSaveFile();
   if(file==null)
   {
    return;
   }
   else
   {
    currentFileName=file;
    SaveFile(textBoxEdit.Text);
    FileInfo f=new FileInfo(currentFileName);
    this.Text="文本编辑--"+f.Name;
    needToSave=false;
   }
  }
  private void SaveFile(string str)
  {
   try
   {
    StreamWriter writer=new StreamWriter(currentFileName);
    writer.Write(str);
    writer.Close();
   }
   catch(Exception e)
   {
    MessageBox.Show(e.Message);
   }
  }
  private string GetSaveFile()
  {
   SaveFileDialog saveFile=new SaveFileDialog();
   saveFile.Title="保存文本文件";
            saveFile.OverwritePrompt=true;
   saveFile.CreatePrompt=true;
   saveFile.AddExtension=true;
   saveFile.Filter="文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
   if(saveFile.ShowDialog()==DialogResult.OK)
   {
    return saveFile.FileName;
   }
   else
   {
    return null;
   }
  }

  private void menuItemFont_Click(object sender, System.EventArgs e)
  {
   FontDialog fontDialog=new FontDialog();
   fontDialog.ShowColor=true;
   fontDialog.AllowScriptChange=true;
   fontDialog.AllowVectorFonts=true;
   fontDialog.ShowEffects=true;
   if(fontDialog.ShowDialog()==DialogResult.OK)
   {
    textBoxEdit.Font=fontDialog.Font;
    textBoxEdit.ForeColor=fontDialog.Color;
   }
  }

  private void menuItemColor_Click(object sender, System.EventArgs e)
  {
   ColorDialog colorDialog=new ColorDialog();
   colorDialog.AllowFullOpen=true;
   colorDialog.AnyColor=true;
   colorDialog.FullOpen=true;
   if(colorDialog.ShowDialog()==DialogResult.OK)
   {
    textBoxEdit.BackColor=colorDialog.Color;
   }
  }

  private void menuItemPrint_Click(object sender, System.EventArgs e)
  {
   PrintDialog printDialog=new PrintDialog();
   printDialog.Document=printDocument;
   if(printDialog.ShowDialog()==DialogResult.OK)
   {
    try
    {
     printDocument.Print();
    }
    catch(Exception e2)
    {
     MessageBox.Show(e2.Message);
    }
   }
  }
  private void printDocument_PrintPage(object sender,PrintPageEventArgs e)
  {
   float linesPerPage=0;
   float yPos=0;
   int count=0;
   float leftMargin=e.MarginBounds.Left;
   float topMargin=e.MarginBounds.Top;
   string line=null;
            StreamReader streamToPrint=new StreamReader(currentFileName);
   SolidBrush brush=new SolidBrush(textBoxEdit.ForeColor);
   linesPerPage=e.MarginBounds.Height/textBoxEdit.Font.GetHeight(e.Graphics);
   while(count<linesPerPage&&((line=streamToPrint.ReadLine())!=null))
   {
    yPos=topMargin+(count*textBoxEdit.Font.GetHeight(e.Graphics));
    e.Graphics.DrawString(line,textBoxEdit.Font,brush,leftMargin,yPos,new StringFormat());
    count++;
   }
   if(line!=null)
   {
    e.HasMorePages=true;
   }
   else
   {
    e.HasMorePages=false;
   }
  }

  private void menuItemPageSet_Click(object sender, System.EventArgs e)
  {
   PageSetupDialog pageSet=new PageSetupDialog();
   pageSet.Document=printDocument;
   pageSet.ShowDialog();
  }

  private void FormMain_Closing(object sender, System.ComponentModel.CancelEventArgs e)
  {
   if(needToSave==true)
   {
    DialogResult result=MessageBox.Show("文本内容已经改变,需要保存吗?","保存文件",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Question);
    if(result==DialogResult.Cancel)
    {
     e.Cancel=true;
     return;
    }
    if(result==DialogResult.Yes)
    {
     menuItemSave_Click(sender,e);
     e.Cancel=false;
     return;
    }
   }
  }

  private void menuItemNew_Click(object sender, System.EventArgs e)
  {
   if(needToSave==true)
   {
    DialogResult result=MessageBox.Show("文本内容已经改变,需要保存吗?","保存文件",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Question);
    switch(result)
    {
     case DialogResult.Yes:
     {
      menuItemSave_Click(sender,e);
      textBoxEdit.Clear();
      this.Text="文本编辑--新建文本";
      needToSave=false;
      break;
     }
     case DialogResult.No:
     {
      textBoxEdit.Clear();
      this.Text="文本编辑--新建文本";
      needToSave=false;
      break;
     }
     case DialogResult.Cancel:
     {
      break;
     }
    }
   }
   else
   {
    textBoxEdit.Clear();
    this.Text="文本编辑新建文本";
   }
  }

 }



<script language="javascript" type="text/javascript"> </script>
以下是WinForm记事本的介绍和演示: WinForm记事本一个Windows应用程序,它可以实现文本的编辑、存储和格式设置等功能。它使用了MenuStrip(菜单)、ToolStrip(工具栏)、RichTextBox(高级文本框)和StatusStrip(状态栏控件)等控件,同时也使用了CommonDialog(公共对话框)实现对文本的存取、格式设置等操作。 该记事本具有以下功能: 1. 文件的新建、打开、保存功能; 2. 文字的复制、粘贴、删除功能; 3. 字体类型、格式的设置功能; 4. 查看日期时间等功能; 5. 用户可以根据需要显示或者隐藏工具栏和状态栏。 以下是WinForm记事本的界面设计步骤: 1. 创建一个新项目; 2. 在窗体上添加MenuStrip、ToolStrip、RichTextBox和StatusStrip等控件; 3. 设置控件的属性,例如菜单项、工具栏按钮、文本框的大小、字体、颜色等; 4. 编写代码实现控件的功能,例如打开、保存、复制、粘贴、删除、字体设置、日期时间显示等。 以下是WinForm记事本的演示代码: ```csharp using System; using System.Windows.Forms; namespace WinFormNotepad { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void newToolStripMenuItem_Click(object sender, EventArgs e) { // 新建文件 } private void openToolStripMenuItem_Click(object sender, EventArgs e) { // 打开文件 } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { // 保存文件 } private void cutToolStripMenuItem_Click(object sender, EventArgs e) { // 剪切文本 } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { // 复制文本 } private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { // 粘贴文本 } private void deleteToolStripMenuItem_Click(object sender, EventArgs e) { // 删除文本 } private void fontToolStripMenuItem_Click(object sender, EventArgs e) { // 设置字体 } private void boldToolStripMenuItem_Click(object sender, EventArgs e) { // 设置加粗 } private void italicToolStripMenuItem_Click(object sender, EventArgs e) { // 设置斜体 } private void underlineToolStripMenuItem_Click(object sender, EventArgs e) { // 设置下划线 } private void dateTimeToolStripMenuItem_Click(object sender, EventArgs e) { // 显示日期时间 } private void toolStripButton1_Click(object sender, EventArgs e) { // 新建文件 } private void toolStripButton2_Click(object sender, EventArgs e) { // 打开文件 } private void toolStripButton3_Click(object sender, EventArgs e) { // 保存文件 } private void toolStripButton4_Click(object sender, EventArgs e) { // 剪切文本 } private void toolStripButton5_Click(object sender, EventArgs e) { // 复制文本 } private void toolStripButton6_Click(object sender, EventArgs e) { // 粘贴文本 } private void toolStripButton7_Click(object sender, EventArgs e) { // 删除文本 } private void toolStripButton8_Click(object sender, EventArgs e) { // 设置字体 } private void toolStripButton9_Click(object sender, EventArgs e) { // 显示日期时间 } } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值