记事本源代码(C#)
记事本代码
PSTR szCmdLine, int iCmdShow )//第三个参数lpCmdLine是一个以空终止的字符串,指定传递给应用程序的命令行参数?
{
static TCHAR szAppName[] = TEXT( "demo" ) ;
return 0 ;
case WM_SIZE:
GetClientRect(hwnd, &rect) ;
MoveWindow( hwndChild[ID_EDITBOX], 0, 0, rect.right, rect.bottom-50, TRUE ) ;//调整文本编辑区
MoveWindow( hwndChild[ID_TXTPATH], 100, rect.bottom-31, 400, 20, TRUE ) ;//调整文本路径输入框
TextOut( hdc, 800, rect.bottom-30, szLineNum, lstrlen(szLineNum) ) ;
EndPaint( hwnd, &ps ) ;
return 0 ;
case WM_COMMAND:
wmId=LOWORD(wParam);
wmEvent=HIWORD(wParam);
return -1 ;
}
else{
fwrite(content, lstrlen(content), sizeof(char), fSvae);
MessageBox(NULL, TEXT("保存成功!"), TEXT("成功"), MB_OK | MB_ICONINFORMATION) ;
C_实验-记事本(带源码)
记事本实验报告一、实验目的创建一个Windows窗体应用程序,实现记事本的基本功能,具体包括新建文件、打开文件、保存文件、查找等功能。
该实验的目的是掌握:(一)窗体程序的开发(二)常用控件的使用(三)常用事件的处理(四)对话框的设计和使用(五)文件访问的基本方法二、实验内容(一)主窗口Form1图1 主窗口主窗口界面如图1所示,功能包括基本编辑操作、主菜单和其它快捷键功能。
1、编辑功能用文本框实现。
2、窗口标题与文件名相一致。
未打开文件时为“无标题”,打开文件(另存为)后为文件名。
3、支持菜单的热键和快捷键。
二者的区别是前者是激活菜单且显示出该菜单项时有效,后者在任何时候有效。
4、实现新建、打开、保存和查找功能。
5、支持F3(查找下一个)。
表1 Form1控件列表using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;namespace WindowsFormsApplication1{public partial class Form1 : Form{public Form2 fm2 = null;public string searchText = "";public Form1(){InitializeComponent();}private void saveFile(){if (textBox1.Text.Length > 0 && textBox1.Modified) {if (MessageBox.Show("想保存文件吗?", "记事本",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Warning) == DialogResult.Yes){SaveFileDialog d = new SaveFileDialog();d.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";if (d.ShowDialog() == DialogResult.OK){FileStream fs = File.OpenWrite(d.FileName);StreamWriter sr = new StreamWriter(fs);sr.Write(textBox1.Text);sr.Flush();fs.Close();}}}}private void文件NToolStripMenuItem_Click(object sender, EventArgs e) {saveFile();textBox1.Text = "";Text = "无标题 - 记事本";}private void OpenFile(){OpenFileDialog d = new OpenFileDialog();d.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";if (d.ShowDialog() == DialogResult.OK){FileStream fs = File.OpenRead(d.FileName);StreamReader sr = new StreamReader(fs);string s;string s1 = "";while ((s = sr.ReadLine()) != null){s1 += s;}textBox1.Text = s1;string fname = d.FileName.Substring(stIndexOf("\\") + 1);Text = fname + " - 记事本";}}private void打开OToolStripMenuItem_Click(object sender, EventArgs e) {saveFile();OpenFile();}private void保存SToolStripMenuItem_Click(object sender, EventArgs e) {saveFile();}private void查找FToolStripMenuItem_Click(object sender, EventArgs e) {if (fm2 == null){fm2 = new Form2();fm2.fm1 = this;Form2.textBox2 = textBox1;fm2.Show();}elsefm2.Activate();}private void textBox1_KeyDown(object sender, KeyEventArgs e){if (e.KeyCode == Keys.A && e.Control && !e.Shift && !e.Alt){textBox1.SelectAll();e.Handled = true;}else if (e.KeyCode == Keys.F3 && !e.Control && !e.Shift && !e.Alt) {Form2.findNext();}}}}(二)查找对话框图2 查找对话框查找对话框的界面(图2)与记事本的相同。
c语言的记事本源代码
if((fp=fopen("tongxunlu.txt","a+"))==NULL)
{ printf(" 无法打开文件~~~\n");
}
while(!feof(fp))
{ i++;
p2=p1;
p1=(link *)malloc(LEN);
printf("Thank your use\n");
else
if(identify=='n'||identify=='N')
exit(0);
else
printf(" 请输入(Y/N):");
{ printf(" 无法打开文件~~~\n");
exit(0);
} //打开文件,并将文件中内容复制到链表中,若文件中无记录,则链表头指针为空
char identify;
// char fullname[10];
link *head,*p,*p1,*p2,*p3;
int choose;
char absorb;
int i;
head=NULL;
welcome();
head=NULL;
p2->next=NULL;
fclose(fp);
if(head==NULL)
p1=p2=(link *)malloc(LEN);
fread(p1,LEN,1,fp);
head=p1;
#include<stdio.h>
#include<stdlib.h>
c语言课设实验报告-记事本程序(含源码)
C语言课设实验报告[记事本程序]班级:学号:姓名:指导老师:C语言课设实验报告#define key_down 80#define key_up 72#define key_esc 1#define key_alt_f 33#define key_alt_x 45#define key_enter 28#define key_alt_e 18int get_key();void box(int startx,int stary,int high,int width);{int i,key,x,y,l;char *w=NULL,*d=NULL,*s=NULL;FILE *fp;char *menu[]={ "File ", "Edit ","Format","View","Help"};char *red[]={ "F", "E","F","V","H"};char *f[]={ "New ", "Open" , "Save", "Another","Quit alt_x"};char *e[]={"Search","Search next","Replace","Date"};char buf[16*10*2],buf1[16*2];textbackground(3);clrscr();window(1,1,80,1);textbackground(WHITE);textcolor(BLUE);clrscr();window(1,1,80,2);for(i=0, l=0; i <5;i++){x=wherex();y=wherey();textcolor(BLACK);cprintf( " %s ",menu[i]);l=strlen(menu[i]);gotoxy(x,y); x.y等的头文件*//*功能键的扫描码的定义*//* i为循环次数的序数,key为从键盘输入的功能键,x,y 为光标的坐标,l为菜单栏中菜单的字符长度*//*w是存放输入的内容(记录的事情)的指针,*s是存放输入的文件名的指针,*d是存放输入要定时的文件的文件名的指针*/ /*菜单栏中各个菜单的定义*//*菜单栏中菜单开头要标颜色的字母的定义*//* file 子菜单中项目的定义*//*edit子菜单的定义*/ /*缓冲区的定义*//*整个大窗口的背景颜色设置*//*创建菜单栏窗口*/ /*设置菜单栏窗口背景颜色为白色,字体颜色为蓝色*//*利用循环输出menu菜单栏,有多少个菜单循环多少次。
C语言记事本代码
C语言记事本代码#include<stdio.h>#include<malloc.h>#include<string.h>#include<stdlib.h>#include<ctype.h>#define NULL 0#define MAX 100typedef struct lnode{char date[MAX]; //存放数据struct lnode * prior ; //前驱struct lnode * next ; //后继int number ; //记录一个节点的字符数~如果是头节点就记录他的节点个数int quese ; //记录节点在链表中的位置}lnodetype;lnodetype * l ; //设置两个全局变量,分别是头节点指针和尾节点指针lnodetype * end ;//**********这个函数是用来初始化的**********//int iniatelist (lnodetype ** l , lnodetype ** end){(*l) = (lnodetype *)malloc (sizeof (lnodetype) ) ;if ( (*l) == NULL ){printf ("没有只够的内存空间~程序即将退出~");return 0 ;}(*l)->prior =(*l)->next = NULL ; //这是双链表(*l)->number = (*l)->quese = 0;(*end) = (*l) ;printf ("程序初始化完毕~");return 0;}//**********这个函数是用来建立节点,并且插入元素的**********// int link(lnodetype ** l, lnodetype ** end){lnodetype *s ;s = (lnodetype *)malloc ( sizeof (lnodetype) ) ;if ( s == NULL ){printf ("内存空间不够,程序即将退出~") ;return 0 ;}(*end)->next = s ;s->prior = (*end) ;(*end) = (*end)->next ;(*l)->number++ ; //增加一个节点,头节点的number就加1s->quese = (*l)->number ; //这个是记录节点在链表中的位置printf ("%d行", s->quese ) ; //这个是节点在整个链表中的位置gets(s->date) ;s -> number = strlen(s->date) ;return 0 ;}//**********这个是打印链表的函数**********//int prin (lnodetype ** l, lnodetype ** end){lnodetype * p ;int i ;int j = 0;int couter = (*l)->number ;p = (*l)->next ;for (i=0; i < couter; i++){printf ( "%d行" , i+1 ) ;j = 0;while ( ( p->date[j]>='a' && p->date[j]<='z') || (p->date[j]>='A' && p->date[j]<='z') ||p->date[j]>='0' && p->date[j]<='9'){printf ( "%c" , p->date[j] ) ;j++ ;}printf ("n") ;p = p->next ;}return 0 ;}//*********这个查找和编辑相应行的函数**********//int search (lnodetype ** l, lnodetype ** end ){int number ;scanf ("%d" , &number) ;int i ;lnodetype * p ;p = (*l)->next ;for ( i=0; i<number-1; i++ )p = p->next ;printf ("%d行" , number ) ;gets (p->date) ;return 0 ;}//**********这个是在文本文件里搜索字符串的函数**********// int searchstr(lnodetype ** l , lnodetype ** end){char ptr[100] ;int arrycouter ;int mystrcmp( char *, char * , int ) ;printf ( "ok!现在输入你查找的字符串~" ) ;scanf ( "%s" , ptr ) ;arrycouter = strlen (ptr) ;lnodetype * s ;s = (*l)->next ;char * p ;int i = 1 ;int couter = 0 ;int number = (*l)->number ;p = (char *)s->date ;while ( i && number ){// i=1是,证明没有找到,向第二个节点继续寻找while ( i && ( ( (*p >= 'a') && (*p <= 'z') ) ||( (*p >= 'A') && (*p <= 'Z') ) ) ){i = mystrcmp ( p , ptr , arrycouter );if ( i == 1 ){printf ("字符串已经在第%d行,第%d个字符开始,",s->quese, couter+1 );i = 0 ;}else{p++ ;couter++;i = 1 ;}}s = s->next ;p = (char *)s->date ;number -- ;}if ( i == 1 )printf ("字符串在本文档中不存在~");return 0 ;}//**********(1)这个函数是用来实现退出不保存功能的**********// int exitunsave(lnodetype ** l, lnodetype ** end){lnodetype * s ;while( (*l) != (*end) ){ //如果不保存的话,最好是把节点的空间都释放,节省空间s = (*end) ;(*end) = (*end)->prior ;free( s ) ;}return 0 ;}//**********(2)这个函数是用来实现退出但保存功能的**********// int quitandsave( lnodetype ** l , lnodetype ** end ){FILE * fp ;char ch ;char filename[20] ;lnodetype * p;int i ;int j ;int couter = (*l)->number ;p = (*l)->next ;printf ("请输入文件名:") ;scanf ("%s" , filename ) ;if ( (fp = fopen( filename , "w" )) == NULL ){printf ("文件不能打开~n");return 0 ;}for ( i=0; i<couter; i++ ){ //有几个节点就进行多少次的存贮ch = p->date[0] ;j = 1 ;while (ch != '\0'){fputc (ch , fp) ;ch = p->date[j] ;j++ ;}p = p->next ;fputc ( '#' , fp ) ; //注意在每个节点的后面加上结束的符号}fputc ( '@' , fp ) ; //整个文件关闭的标志fclose ( fp ) ; //注意关闭文件,return 0 ;}//**********由于库函数比较字符串提供的功能不满足要求,故自己写了一个**********/int mystrcmp( char * p ,char * sour ,int number ){while ( number && (*p) == (*sour) &&( ( (*p >= 'a') && (*p <= 'z') ) || ( (*p >= 'A')&& (*p <= 'Z') ) )){p++ ;sour++ ;number-- ;}if ( number == 0 )return 1 ;elsereturn 0 ;}//**********这个函数是用来实现统计字符串功能的**********//int coutword(lnodetype ** l , lnodetype ** end){ //考虑到只统计一行的单词没有意义,故统计整个文本int yes = 1 ; //这个是进入单词的标志int no = 0 ; //在单词外面的时候的标志int i , j ,inaword ,count = 0 ;inaword = no ;lnodetype * s = (*l)->next ;for (j=0; j<(*l)->number; j++){for ( i=0; (s->date[i]>='a' && s->date[i]<='z') || (s->date[i]>='A' && s->date[i]<='z') ||(s->date[i]>='0' && s->date[i]<='9' ) ||(s->date[i]==' '); i++ ){if ( s->date[i] == ' ' )inaword = no ;elseif ( inaword == no ){inaword = yes ;count++ ; //计算单词}}s = s->next ;inaword = 0 ; //注意这里,把标志置为0了~}printf ( "n文本一共有 %d 行" , (*l)->number ) ;printf ("n此文本一共有 %d 个单词!" , count ) ;return count ;}//**********这个函数是用来实现计算文本行数功能的**********// int linecouter(lnodetype ** l , lnodetype ** end ){int couter ;couter = (*l)->number ;return couter ;}//**********这个函数是整和一上所有功能的菜单函数**********// int editmenu(lnodetype ** l , lnodetype ** end ){char choice ;char * p = "cls" ;int i = 1 ; //这两个变量是用来控制循环的int j= 1 ;system (p) ;prin (&(*l) , &(*end)) ;while (j){printf ("*********************************** e: 编辑相应行*************************************n") ;printf ("*********************************** s: 搜索字符串*************************************n") ;printf ("*********************************** t: 统计单词个数***********************************n") ;printf ("*********************************** q: 退出编辑***************************************n") ;scanf("%c",&choice);scanf("%c" , &choice) ; //,,,,莫名其妙的问题,非要两个请求输入语句才肯停下来~switch (choice){case 'e' : {i = 1 ;while (i){search( &(*l) , &(*end) );system (p) ;prin( &(*l) , &(*end) ) ;printf ("n1 继续编辑 0 结束编辑n") ;scanf ("%d" , &i) ;}}break;case 's' : {i = 1 ;while (i){searchstr( &(*l) , &(*end) );getchar();getchar();system (p) ;prin( &(*l) , &(*end) ) ;printf ("n1 继续搜索 0 结束搜索n") ; scanf ("%d" , &i) ;}}break;case 't' : {coutword ( &(*l) , &(*end) ) ;getchar() ;}break;default : return 0 ;}system (p) ;prin( &(*l) , &(*end) ) ;printf ("n1 回到编辑菜单 0 结束编辑n") ; scanf ("%d" , &j) ;if (j == 1)system (p) ;elsereturn 0 ;}return 0 ;}//**********实现第一个模块:新建空白文档**********// int newtext( lnodetype ** l ,lnodetype ** end ) {printf ( "新文本文件:n" ) ;int i = 1 ;char judstr[MAX] ;lnodetype * temp ;char jud ;char * p = "cls" ;while ( 1 ){link( &(*l) , &(*end) ) ;jud = (*end)->date[0] ;if ( jud == '5' ){ //输入‘5’结束一切temp = (*end) ;(*end) = (*end)->prior ;free (temp) ;while (1){printf ( "******************************* out :退出不保存****************************n") ;printf ( "******************************* edit :编辑信息*****************************n") ;printf ( "******************************* quit :退出而不存盘**************************n") ;printf ( "******************************* qas :退出且存盘****************************n") ;printf ( "******************************* con :继续输入~*****************************n") ;gets(judstr) ;if ( !strcmp(judstr , "out") ){exitunsave( &(*l) , &(*end) ) ;return 0 ;}elseif ( !strcmp(judstr , "qas") ){quitandsave( &(*l) , &(*end) ) ;return 0 ;}elseif ( !strcmp(judstr , "edit") ){editmenu (l , end) ;return 0;}system (p) ;}return 0 ;}}return 0 ;}//**********这个是装入文件的函数**********// int loadtaxt( char * filename ){FILE * fp ;lnodetype * l ;char ch ;int i = 0 ;char * p = "cls" ;char judstr[MAX] ;lnodetype * head ;lnodetype * end ;iniatelist ( &head , &end) ;l = end = head ;if ( (fp = fopen( filename, "r+")) == NULL ){ printf ("文件不能打开~n") ;return 0 ;}ch = fgetc ( fp ) ;while ( ch != '@' ){lnodetype *s ;s = (lnodetype *)malloc ( sizeof (lnodetype) ) ; if ( s == NULL ){printf ("内存空间不够,程序即将退出~") ;return 0 ;}end->next = s ;s->prior = end ;end = end->next ;l->number++ ;s->quese = l->number ;printf ("%d行", s->quese ) ;while ( ch != '#'){s->date[i] = ch ;ch = fgetc (fp) ;i++ ;}i = 0;while ( (end->date[i]>='a' && end->date[i]<='z') ||(end->date[i]>='A' && end->date[i]<='z') ||(end->date[i]>='0' && end->date[i]<='9' ) ||(end->date[i]==' ') ){printf ( "%c" , end->date[i] ) ;i++ ;}end->date[i] = '\0' ; //注意在节点的最好加上这个,以让退出保存功能函数知道此节点已结束printf ( "n" ) ;i = 0;ch = fgetc ( fp ) ;}fclose (fp) ;printf ("n文件成功装入~n") ;while (1){printf ( "******************************* out :退出不保存****************************n") ;printf ( "******************************* edit :编辑信息*****************************n") ;printf ( "******************************* qas :退出且存盘****************************n") ;printf ( "******************************* con :继续输入~*****************************n") ;scanf("%s",judstr);if ( !strcmp(judstr , "out") ){exitunsave( &l , &end ) ;return 0 ;}elseif ( !strcmp(judstr , "qas") ){quitandsave( &l , &end ) ;return 0 ;}elseif ( !strcmp(judstr , "edit") ){editmenu (&l , &end) ;return 0 ;}system (p) ;}return 0 ;}//**********主函数**********// void main ( void ){//iniatelist (&l , &end) ;//newtext(&l , &end) ;char filename[MAX] ;scanf ( "%s" , filename ) ; loadtaxt( filename ) ;}很不容易做的程序~~~通过编译。
记事本源代码
记事本源代码先上效果图。
这个记事本操作简便,功能强⼤,在记事本的基础上添加了将内容发送短信和发送邮件的功能。
这个应⽤也已经功过了微软的认证。
115⽹盘⾥⾯的是最新的。
QQ:29992379下载地址:Memo.xap实体类1: public class Note2: {3: public string NoteGuid { get; set; }4: public string NoteContent { get; set; }5: public string NoteTime { get; set; }6: }在独⽴存储中⽣成存储结构。
1: if (!IsolatedStorageSettings.ApplicationSettings.Contains("Notes"))2: {3: List<Note> notes = new List<Note>();4: IsolatedStorageSettings.ApplicationSettings["Notes"] = notes as List<Note>;5: IsolatedStorageSettings.ApplicationSettings.Save();6:7: }绑定⽂章的列表,并按编号倒排序。
1: public partial class MainPage : PhoneApplicationPage2: {3: // 构造函数4: public MainPage()5: {6: InitializeComponent();7: BingData();8: }9: List<Note> notes = new List<Note>();10: private void BingData()11: {12: notes = IsolatedStorageSettings.ApplicationSettings["Notes"] as List<Note>;13:14: var descInfo = from i in notes orderby i.NoteTime descending select i;//linq对⽂章列表的排序15:16: MainListBox.ItemsSource = descInfo;17: }18:19: private void ApplicationBarIconButton_Click(object sender, EventArgs e)20: {21: NavigationService.Navigate(new Uri("/Add.xaml", UriKind.RelativeOrAbsolute));22: }23:24: protected override void OnBackKeyPress(ponentModel.CancelEventArgs e)25: {26: e.Cancel = true;27: App.Quit();28: base.OnBackKeyPress(e);29: }30:31: private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)32: {33: NavigationService.Navigate(new Uri("/About.xaml", UriKind.RelativeOrAbsolute));34: }35:36: private void StackPanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)37: {38: string noteguid = ((TextBlock)(((StackPanel)sender).Children.First())).Tag.ToString();39: NavigationService.Navigate(new Uri("/DetailsPage.xaml?noteguid=" + noteguid, UriKind.Relative));40: }41: }⽂章显⽰的页⾯以及⼀系列功能1: public partial class DetailsPage : PhoneApplicationPage2: {3: // 构造函数4: public DetailsPage()5: {6: InitializeComponent();7: }8: string noteguid;9: protected override void OnNavigatedTo(NavigationEventArgs e)10: {11: BingData();12: noteguid = NavigationContext.QueryString["noteguid"].ToString();13: foreach (var item in notes)14: {15: if (item.NoteGuid==noteguid)16: {17: ContentText.Text = item.NoteContent;18: TimeText.Text = item.NoteTime;19: return;20: }21: }22: }23:24: List<Note> notes = new List<Note>();25: private void BingData()26: {27: notes = IsolatedStorageSettings.ApplicationSettings["Notes"] as List<Note>;28: }29:30: private void Edit_Click(object sender, EventArgs e)31: {32: NavigationService.Navigate(new Uri("/Edit.xaml?noteguid=" + noteguid.ToString(), UriKind.RelativeOrAbsolute)); 33: }34:35: protected override void OnBackKeyPress(ponentModel.CancelEventArgs e)36: {37: e.Cancel = true;38: NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));39: base.OnBackKeyPress(e);40: }41:42: private void Del_Click(object sender, EventArgs e)43: {44: for (int i = 0; i < notes.Count; i++)45: {46: if (notes[i].NoteGuid==noteguid)47: {48: notes.RemoveAt(i);49: }50: }51: IsolatedStorageSettings.ApplicationSettings["Notes"] = notes as List<Note>;52: IsolatedStorageSettings.ApplicationSettings.Save();53: NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));54: }55:56: private void Email_Click(object sender, EventArgs e)57: {58: EmailComposeTask email = new EmailComposeTask();59: email.Body = ContentText.Text.ToString();60: email.Show();61: }62:63: private void Message_Click(object sender, EventArgs e)64: {65: SmsComposeTask sms = new SmsComposeTask();66: sms.Body = ContentText.Text.ToString();67: sms.Show();68: }69: }⽂章的编辑页⾯代码1: public partial class Edit : PhoneApplicationPage2: {3: public Edit()4: {5: InitializeComponent();6: }7:8: private void ApplicationBarIconButton_Click(object sender, EventArgs e)9: {10: foreach (var item in notes)11: {12: if (item.NoteGuid == noteguid)13: {14: item.NoteContent = ContentText.Text;15: item.NoteTime=TimeText.Text;16: }17: }18:19: IsolatedStorageSettings.ApplicationSettings["Notes"] = notes as List<Note>;20: IsolatedStorageSettings.ApplicationSettings.Save();21: NavigationService.Navigate(new Uri("/DetailsPage.xaml?noteguid=" + noteguid.ToString(), UriKind.RelativeOrAbsolute)); 22: }23: string noteguid;24: protected override void OnNavigatedTo(NavigationEventArgs e)25: {26: BingData();27: noteguid = NavigationContext.QueryString["noteguid"].ToString();28: foreach (var item in notes)29: {30: if (item.NoteGuid==noteguid)31: {32: ContentText.Text = item.NoteContent;33: TimeText.Text = item.NoteTime;34: return;35: }36: }37: }38:39: List<Note> notes = new List<Note>();40: private void BingData()41: {42: notes = IsolatedStorageSettings.ApplicationSettings["Notes"] as List<Note>;43: }44: }。
纯C++代码写的记事本
#include "windows.h"#include "wyyapi.h"#include "inttypes.h"#include <string>#include "stdio.h"LRESULT CALLBACK MainWndProc(HWND,UINT,WPARAM,LPARAM);HMENU wyymenu=NULL;int i=0;BOOL CreateTopMenu(){wyymenu=CreateMenu();HMENU wyypopup=CreateMenu();HMENU wangpopup=CreateMenu();AppendMenu(wyypopup,MF_STRING,IDM_OPEN,"&打开");AppendMenu(wyypopup,MF_STRING,IDM_EXIT,"&退出");AppendMenu(wangpopup,MF_STRING,IDM_NEW,"&刷新");AppendMenu(wangpopup,MF_STRING,IDM_SAVE,"&保存");AppendMenu(wyymenu,MF_POPUP,(intptr_t)wyypopup,"&王云勇");AppendMenu(wyymenu,MF_POPUP,(intptr_t)wangpopup,"&王云");return true;}int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow){char wclassname[]="wyy";WNDCLASSEX wc;wc.cbSize=sizeof(WNDCLASSEX);wc.style=CS_HREDRAW|CS_VREDRAW|CS_NOCLOSE;wc.lpfnWndProc=MainWndProc;wc.cbClsExtra=0;wc.cbWndExtra=0;wc.hInstance=hInstance;wc.hIcon=LoadIcon(hInstance,(LPSTR)IDI_MAIN);wc.hCursor=LoadCursor(NULL,IDC_ARROW);wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);wc.lpszMenuName=NULL;wc.lpszClassName=wclassname;wc.hIconSm=LoadIcon(hInstance,(LPSTR)IDI_MAIN);RegisterClassEx(&wc);CreateTopMenu();HWND hwnd=CreateWindowEx(WS_EX_LEFT,wclassname,"王云勇首富",WS_CAPTION,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,wyymenu,hInstance,NULL);if(hwnd==NULL){MessageBox(NULL,"窗口出错","error",MB_OK);return -1;}ShowWindow(hwnd,nCmdShow);UpdateWindow(hwnd);MSG msg;while(GetMessage(&msg,NULL,0,0)){TranslateMessage(&msg);DispatchMessage(&msg);}return msg.wParam;}LRESULT CALLBACK MainWndProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam){FILE *wyywy;static int i=0;HDC hdc;PAINTSTRUCT ps;static std::string str;static char *sf;static wchar_t *sfwyy;OPENFILENAME ofn;static char szFile[256];static char szFileTitle[256];memset(&ofn,0,sizeof(ofn));ofn.lStructSize=sizeof(ofn);ofn.hwndOwner=hwnd;ofn.lpstrFilter="保存的文件(*.txt)\0*.txt\0\0";ofn.nFilterIndex=1;ofn.lpstrFile=szFile;ofn.nMaxFile=sizeof(szFile);ofn.lpstrFileTitle=szFileTitle;ofn.nMaxFileTitle=sizeof(szFileTitle);ofn.Flags=OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST|OFN_EXPLORER;switch(message){case WM_COMMAND:switch(LOWORD(wParam))MessageBox(hwnd,TEXT("王云勇"),TEXT("首富"),MB_OK); break;case IDM_EXIT:exit(0);break;case IDM_NEW:{str.clear();i=i+8;InvalidateRect(hwnd,NULL,1);}break;case IDM_SAVE:{if(GetSaveFileName(&ofn)){sf=ofn.lpstrFile;strcat(sf,".txt");size_t len=strlen(sf)+1;size_t con=0;sfwyy=(wchar_t*)malloc(len*sizeof(wchar_t));mbstowcs_s(&con,sfwyy,len,sf,_TRUNCATE);if((wyywy=_wfopen(sfwyy,L"wt+"))==NULL){MessageBox(hwnd,TEXT("出错"),TEXT("首富"),MB_OK); MessageBox(hwnd,TEXT("返回"),TEXT("首富"),MB_OK); break;}_wsetlocale(0,L"chs");if(fwprintf(wyywy,L"%s",str)>0){MessageBox(hwnd,TEXT("保存成功"),TEXT("首富"),MB_OK);} if(fclose(wyywy)==0){MessageBox(hwnd,TEXT("王云勇成功"),TEXT("首富"),MB_OK);} }}default:break;}break;case WM_PAINT:{hdc=BeginPaint(hwnd,&ps);if(i==0){TextOut(hdc,0,0,str.c_str(),str.length());}EndPaint(hwnd,&ps);}break;{i=0;str=str+char(wParam);InvalidateRect(hwnd,NULL,0);return 0;}case WM_DESTROY:PostQuitMessage(0);return 0;}return DefWindowProc(hwnd,message,wParam,lParam); }。
记事本代码
记事本代码#include<iostream.h>#include<string.h>#include<ctype.h> //为了以下使用isdigit(string)函数作铺垫typedef struct node{char a[100]; //每行100字符node * next; //关于此处next的作用还不清楚,但不可去掉}node;class notepad{public:notepad(){i=1;line=0;}~notepad(){}void operator_interface();void input();void ct_input();void delete1();void copy();void paste();void open();void save();char * find();void print();char store[100]; //储存需复制内容private:char * ptr_array[100]; //指针数组,记录100行行指针int linelen[100]; //最大100行int line; //当前总行数char d[30]; //记录操作数据int k,l; //记录当前查找行ilint i; //文档录入初始标记};void notepad::operator_interface(){cout<<"********************************************************"<<en dl;cout<<"***0.继续录入文档"<<endl;cout<<"***1.输入文档内容"<<endl;cout<<"***2.删除某些内容"<<endl;cout<<"***3.复制某些内容"<<endl;cout<<"***4.粘贴某些内容"<<endl;cout<<"***5.打开文档内容"<<endl;cout<<"***6.是否保存文档"<<endl;cout<<"***7.获取操作帮助"<<endl;cout<<"***8.我要结束操作"<<endl;cout<<"********************************************************"<<en dl;}void notepad::input(){-99"<<endl; cout<<"输入总行数,格式:01char e[10];cin>>e;char *lin=e;if(*(lin+2)=='\0'&&isdigit(*lin)&&isdigit(*(lin+1))){line=(*lin-'0')*10+(*(lin+1)-'0');if(line!=0){cout<<"请输入各行内容"<<endl;while(i<=line){cout<<"第"<<i<<"行 ";node *p=new node;cin>>p->a;ptr_array[i]=p->a;linelen[i]=strlen(p->a);i++;}}else cout<<"你输入的行数有误"<<endl;}else cout<<"你输入的行数有误"<<endl; }void notepad::ct_input(){if(line!=0){int i=line+1;cout<<"输入要录入的总行数,格式:01-99"<<endl;char e[10];cin>>e;char *lin=e;if(*(lin+2)=='\0'&&isdigit(*lin)&&isdigit(*(lin+1))){ line=line+(*lin-'0')*10+(*(lin+1)-'0');if(line!=0){cout<<"请输入各行内容"<<endl;while(i<=line){cout<<"第"<<i<<"行 ";node *p=new node;cin>>p->a;ptr_array[i]=p->a;linelen[i]=strlen(p->a);i++;}}else cout<<"你输入的行数有误"<<endl;}else cout<<"你输入的行数有误"<<endl;}else cout<<"当前文档并无内容,请先输入1录入文档"<<endl; }void notepad::print(){cout<<endl<<endl;int j=1;cout<<"当前文档内容为:"<<endl;while(j<=line){cout<<"第"<<j<<"行 ";char *q=ptr_array[j];while(*q!='\0'){cout<<*q;q++;}cout<<endl;j++;}cout<<endl;}char * notepad::find(){ //暂未解决跨行查找问题k=1;cin>>d;l=strlen(d);char *n=d;int c=1;char *m=ptr_array[k];while(k<=line){if(*m=='\0'){k=k+1;if(k<=line)m=ptr_array[k];}if(*m!='\0'&&*m!=*n)m++;while(*n!='\0'&&*m!='\0'&&*m==*n){ m=m+1;n=n+1;c=c+1;}if(*n=='\0'){return m-c+1;}else {n=d;c=1;}}return NULL;}void notepad::delete1(){char * dp1;char * dp2;cout<<"请输入要删除的文本前几位字符,注意区分"<<endl;dp1=find();int l1=k;cout<<"请输入要删除的文本末几位字符,注意区分"<<endl;dp2=find();int l2=k;if(dp1==NULL||dp2==NULL||l1>l2)cout<<"输入错误"<<endl;else{dp2=dp2+l;if(l1==l2){while(*dp2!='\0'){*dp1=*dp2;dp1++;dp2++;}*dp1='\0';linelen[l1]=strlen(ptr_array[l1]);}else {if(l1+1<l2){for(intt1=l1+1,t2=l2;t2<=line;t1++,t2++)ptr_array[t1]=ptr_array[t2]; line=line-l2+l1+1;l2=l1+1;}*dp1='\0';char *dp21=ptr_array[l2];while(*(dp2-1)!='\0'){*dp21=*dp2;dp21++;dp2++;}linelen[l1]=strlen(ptr_array[l1]);linelen[l2]=strlen(ptr_array[l2]);}if(linelen[l1]==0){for(int v=l1;v<=line;v++)ptr_array[v]=ptr_array[v+1]; line--;}if(linelen[l2]==0){for(int v=l2;v<=line;v++)ptr_array[v]=ptr_array[v+1]; line--;}}}void notepad::copy(){char * cp1;char * cp2;cout<<"请输入要复制的文本前几位字符,注意区分"<<endl; cp1=find();int l1=k;cout<<"请输入要复制的文本末几位字符,注意区分"<<endl; cp2=find();int l2=k;char *pt=store;if(cp1!=NULL&&cp2!=NULL&&l1<=l2){cp2=cp2+l;while(cp1!=cp2){if(*cp1=='\0'){l1++;cp1=ptr_array[l1];}else {*pt=*cp1;pt++;cp1++;}}*pt='\0';}else cout<<"输入错误"<<endl; }void notepad::paste(){cout<<"请输入要粘贴位置的前几位字符(在首字符后粘贴)"<<endl; char *pat=find();if(pat!=NULL){int choice2;cout<<"请选择要粘贴内容:1/从内存中0/我自己输入"<<endl; cin>>choice2;if(!choice2)cin>>store;char *ppt=store;for(char *pat1=pat;*(pat1+1)!='\0';pat1++); //定位至末尾int pl=strlen(store);*(pat1+pl+1)='\0';while(pat1!=pat){ //移位*(pat1+pl)=*pat1;pat1--;}pat++;for(int u=1;u<=pl;u++){*pat=*ppt;ppt++;pat++;}linelen[k]=linelen[k]+pl;}else cout<<"输入错误"<<endl;}void notepad::open(){print();}void notepad::save(){cout<<"是否保存文件,1/是0/否"<<endl;char g[10];int choice1;cin>>g;char *choi=g;if(*(choi+1)=='\0'&&isdigit(*choi)){ choice1=*choi-'0';if(choice1==1)cout<<"文件已保存"<<endl; else if(choice1==0){for(int w=1;w<=line;w++){ //相当于析构函数的作用ptr_array[w]=NULL;linelen[w]=0;}line=0;}else cout<<"输入错误"<<endl;}else cout<<"输入错误"<<endl; }void main(){cout<<"欢迎使用本程序,您可以在要输入文档内容时通过切换输入法实现输入汉字,byhk"<<endl;notepad b;b.operator_interface();char f[10];int choice;cin>>f;char *choic=f;if(*(choic+1)=='\0'&&isdigit(*choic)){ //错误输入处理机制choice=*choic-'0';}else choice=9;while(choice!=8){switch(choice){case 0:b.ct_input();break;case 1:b.input();break;case 2:b.delete1();b.print();break;case 3:{b.copy();cout<<endl;char *p_t=b.store;int fzcd=strlen(b.store);cout<<"你所要复制的内容长度为"<<endl<<fzcd<<endl; cout<<"你所要复制的内容为"<<endl;while(*p_t!='\0'){cout<<*p_t;p_t++;}cout<<endl;}break;case 4:b.paste();b.print();break;case 5:b.open();break;case 6:b.save();break;case 7:b.operator_interface();break;case 8:break;default:break;}if(choice==9||(choice>=0&&choice<=7)){ //输入错误时的操作及输入正确时 //的继续操作判断if(choice==9)cout<<"你输入的操作有误,请重新输入,输入 7 获取操作帮助"<<endl;else cout<<"继续你的操作,输入 7 获取操作帮助"<<endl;cin>>f;choic=f;if(*(choic+1)=='\0'&&isdigit(*choic)) //错误输入处理机制choice=*choic-'0';else choice=9;}}cout<<"感谢您的使用"<<endl; }。
用C#语言实现记事本(代码)
一记事本本章介绍如何使用Visual C# 2013设计一个Windows应用程序——记事本,通过本章的学习,可以进一步掌握MenuStrip(菜单)、ToolStrip(工具栏)、RichTextBox(高级文本框)和StatusStrip(状态栏控件)等控件的使用,以及如何使用CommonDialog(公共对话框)实现对文本的存取、格式设置等操作。
(说明:所有代码必须在英文状态下使用!)1.1 记事本简介记事本是一种常用的软件,在微软的Windows中,自带了一个记事本软件,Windows 7下的记事本软件如图1所示。
图1 Windows自带的记事本本章介绍的记事本,实现了Windows自带的记事本的部分功能外,并且还可以任意更改字体的字体类型、大小和颜色,并在状态栏中显示时间。
为了方便用户的操作,还在程序的窗体上放置了一个工具栏。
本章介绍的记事本程序具有文件的新建、打开、保存功能;文字的复制、粘贴、删除功能;字体类型、格式的设置功能;查看日期时间等功能,并且用户可以根据需要显示或者隐藏工具栏和状态栏。
接下来将详细的介绍记事本程序的设计与实现的步骤和方法。
1.2 记事本界面设计新建一个Windows窗体应用程序,并命名为“Notepad”。
本节介绍记事本程序的界面设计以及界面上各控件的属性设置。
1.打开VS2013 单击文件→新建→项目2.选择模版→Visual C# →windows→windows窗体应用程序在下面的名称写Notepad出现界面如图所示3 更改窗体名称单击窗体,→右下角属性→text 修改为“记事本”如图所示控件类型控件名称属性设置结果Form Form1 Name frmNotepadText 记事本StartPosition(起始位置)CenterScreen(中央屏幕)Size 600, 450 Anchor (抛锚,使固定)(1)界面设计新建好“Notepad”项目后,定位到记事本程序的窗体设计器窗口,然后依次在窗体上放置以下控件(各1个):(1)M enuStrip(菜单控件)。
c#记事本 源代码
private ponentModel.Container components = null;
public Form1()
{
InitializeComponent();
this.menuItem3.Index = 1;
this.menuItem3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
namespace NotePad
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private void InitializeComponent()
{
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem6.Shortcut = System.Windows.Forms.Shortcut.CtrlN;
this.menuItem6.Text = "新建(&N)";
this.menuItem6.Click += new System.EventHandler(this.menuItem6_Click);
this.menuItem7.Click += new System.EventHandler(this.menuItem7_Click);
记事本源代码
//记事本源代码package jishiben;import java.awt.*;import javax.swing.*;import javax.swing.event.ListSelectionEvent;import javax.swing.event.ListSelectionListener;import java.awt.event.*;import java.io.*;import java.util.Calendar;import jishiben.FWindow.StyleDialog;public class FristWindow {public static void main(String[] args) {// TODO Auto-generated method stubnew FWindow("记事本");}}class FWindow extends JFrame implements ActionListener,WindowListener,ItemListener { public static Frame frame;JMenuBar menuBar;JPopupMenu menu;//用户在菜单栏上选择项时显示的菜单JMenu menu1,menu2,menu3,menu4,menu5;JMenuItemitem1,item2,item3,item4,item5,item21,item22,item23,item24,item25,item26,item27,item31,item3 2,item41,item51,item52;JMenuItem itemCopy,itemCut,itemPaste;JTextArea text;//显示纯文本的多行区域JScrollPane scrollPane;JComboBox listFont,listFSize;int save_status=0,status=0,huanhang_count=0;FWindow(String s){//窗口的监听addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent event)//关闭窗口的事件{if(save_status==0){//JOptionPane弹出要求用户提供值或向其发出通知的标准对话框//showConfirmDialog询问一个确认问题int check=JOptionPane.showConfirmDialog(null,"文件的文字已经改变,想保存文件吗?","警告",JOptionPane.YES_NO_CANCEL_OPTION);if(check==0){saveFile(status);}if (check==1) {System.exit(0);}if (check==2) {dispose();}}}});//位置setTitle("记事本");setSize(700,400);setLocation(120, 120);menuBar=new JMenuBar();setJMenuBar(menuBar);text=new JTextArea(30,40);text.setLineWrap(true);//滚动条scrollPane=new JScrollPane(text);//文本框的滚动条add(scrollPane);scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWA YS);scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);menu=new JPopupMenu();menu1=new JMenu("文件");menu1.addActionListener(this);//监听文件菜单menu2=new JMenu("编辑");menu3=new JMenu("格式");menu4=new JMenu("查看");menu5=new JMenu("帮助");menuBar.add(menu1);menuBar.add(menu2);menuBar.add(menu3);menuBar.add(menu4);menuBar.add(menu5);//文件菜单下菜单项的创建并监听item1=new JMenuItem("新建");item1.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getSource()==item1) {text.setText("");this.setTitle("无标题- 记事本");}}private void setTitle(String string){// TODO Auto-generated method stub}});//文件菜单下菜单项的打开并监听item2=new JMenuItem("打开");item2.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getSource()==item2) {File fl;JFileChooser jfc1=new JFileChooser("F:/");//选择打开文件的位置int num1=jfc1.showOpenDialog(null);if (num1==JFileChooser.APPROVE_OPTION) {try {fl=jfc1.getSelectedFile();this.setTitle(fl.getName());FileReader fr=new FileReader(fl);BufferedReader br=new BufferedReader(fr);String str;while((str=br.readLine())!=null){text.setText(str);}fr.close();br.close();} catch (FileNotFoundException e1) {// TODO: handle exceptione1.printStackTrace();}catch (IOException e2) {// TODO: handle exceptione2.printStackTrace();}}}}//p12方法private void setTitle(String name){}});//文件菜单下菜单项的保存并监听item3=new JMenuItem("保存");item3.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getSource()==item3) {File f2=null;JFileChooser jfc2=new JFileChooser();int num2=jfc2.showSaveDialog(null);if(num2==JFileChooser.APPROVE_OPTION){f2=jfc2.getSelectedFile();this.setTitle(f2.getName());try {FileWriter fw=new FileWriter(f2);BufferedWriter bw=new BufferedWriter(fw);bw.write(text.getText());bw.close();fw.close();} catch (IOException e2) {// TODO: handle exceptione2.printStackTrace();}}}}private void setTitle(String name){}});//另存为、退出//===================================另存为有问题===============================================//item4=new JMenuItem("另存为...");item4.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stub/*if (e.getActionCommand().equals(" 另存为")) {Frame f=new Frame(" 保存");FileDialog fd=new FileDialog(f," 文件另存为",FileDialog.SA VE);fd.setVisible(true);try {String savepath=fd.getDirectory();String savename=fd.getFile();if (savename!=null) {PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter(savepath+savename)));pw.write(text.getText(),0,text.getText().length());pw.flush();}} catch (Exception easve) {// TODO: handle exception}}*/if (e.getSource()==item4) {File f3=null;JFileChooser jfc3=new JFileChooser();int num3=jfc3.showSaveDialog(null);if(num3==JFileChooser.APPROVE_OPTION){f3=jfc3.getSelectedFile();this.setTitle(f3.getName());try {FileWriter fw=new FileWriter(f3);BufferedWriter bw=new BufferedWriter(fw);bw.write(text.getText());bw.close();fw.close();} catch (IOException e2) {// TODO: handle exceptione2.printStackTrace();}}}}private void setTitle(String name){}});item5=new JMenuItem("退出");//文件菜单下菜单项的退出并监听item5.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getSource()==item5) {int a=JOptionPane.showConfirmDialog(null,"文件已被改变,是否保存?","提示",JOptionPane.YES_NO_CANCEL_OPTION);if (a==1) {this.dispose();}else if(a==0){File f2=null;JFileChooser jfc2=new JFileChooser();int num2=jfc2.showSaveDialog(null);if (num2==JFileChooser.APPROVE_OPTION) {f2=jfc2.getSelectedFile();this.setTitle(f2.getName());try {FileWriter fw=new FileWriter(f2);BufferedWriter bw=new BufferedWriter(fw);bw.write(text.getText());bw.close();fw.close();} catch (IOException e2) {// TODO: handle exceptione2.printStackTrace();}this.dispose();}}}}private void setTitle(String name){}private void dispose(){}});//KeyStroke 仅能对应于按下或释放某个特定的键//返回KeyStroke 的实例,指定该键在按下或释放时是否视为已激活//CTRL_MASK Ctrl 键修饰符常量。
用C编写的记事本程序
最近想好好研究C,于是便拿记事本这个小程序练练手。
自己从网上找了一个挺不错的,就从这个开始学习吧。
一:代码先建立一文件夹->方便管理与查看拿我来说,在d盘根目录下新建note文件夹1.新建一note.rc资源文件,代码如下。
#include "sample.h"A ICON MOVEABLE PURE LOADONCALL DISCARDABLE "sample.ico" //LOADONCALL 调入装入MAINMENU MENU{POPUP "文件(&F)"{MENUITEM "打开(&O)...", CM_FILE_OPENMENUITEM "另存为(&S)...", CM_FILE_SAVEASMENUITEM SEPARATORMENUITEM "关闭", CM_FILE_EXIT}POPUP "帮助(&H)"{MENUITEM "关于(&A)", CM_ABOUT}}2.新建sample.h,代码如下#define CM_FILE_SAVEAS 9072#define CM_FILE_EXIT 9071#define CM_FILE_OPEN 9070#define CM_ABOUT 90693.新建源程序note.c ,代码如下#include <windows.h>#include "sample.h"static char g_szClassName[] = "MyWindowClass";static HINSTANCE g_hInst = NULL;#define IDC_MAIN_TEXT 1001BOOL LoadFile(HWND hEdit, LPSTR pszFileName){HANDLE hFile;BOOL bSuccess = FALSE;hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);if(hFile != INVALID_HANDLE_VALUE){DWORD dwFileSize;dwFileSize = GetFileSize(hFile, NULL);if(dwFileSize != 0xFFFFFFFF){LPSTR pszFileText;pszFileText = (LPSTR)GlobalAlloc(GPTR, dwFileSize + 1);if(pszFileText != NULL){DWORD dwRead;if(ReadFile(hFile, pszFileText, dwFileSize, &dwRead, NULL)){pszFileText[dwFileSize] = 0;if(SetWindowText(hEdit, pszFileText))bSuccess = TRUE;}GlobalFree(pszFileText);}}CloseHandle(hFile);}return bSuccess;}BOOL SaveFile(HWND hEdit, LPSTR pszFileName){HANDLE hFile;BOOL bSuccess = FALSE;hFile = CreateFile(pszFileName, GENERIC_WRITE, 0, 0,CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);if(hFile != INVALID_HANDLE_VALUE){DWORD dwTextLength;dwTextLength = GetWindowTextLength(hEdit);if(dwTextLength > 0)LPSTR pszText;pszText = (LPSTR)GlobalAlloc(GPTR, dwTextLength + 1);if(pszText != NULL){if(GetWindowText(hEdit, pszText, dwTextLength + 1)){DWORD dwWritten;if(WriteFile(hFile, pszText, dwTextLength, &dwWritten, NULL))bSuccess = TRUE;}GlobalFree(pszText);}}CloseHandle(hFile);}return bSuccess;}BOOL DoFileOpenSave(HWND hwnd, BOOL bSave){OPENFILENAME ofn;char szFileName[MAX_PATH];ZeroMemory(&ofn, sizeof(ofn));szFileName[0] = 0;ofn.lStructSize = sizeof(ofn);ofn.hwndOwner = hwnd;ofn.lpstrFilter = "文本文件(*.txt)\0*.txt\0所有文件(*.*)\0*.*\0\0";ofn.lpstrFile = szFileName;ofn.nMaxFile = MAX_PATH;ofn.lpstrDefExt = "txt";if(bSave){ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;if(GetSaveFileName(&ofn))if(!SaveFile(GetDlgItem(hwnd, IDC_MAIN_TEXT), szFileName)){MessageBox(hwnd, "保存文件失败.", "错误信息",MB_OK | MB_ICONEXCLAMATION);return FALSE;}}}else{ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;if(GetOpenFileName(&ofn)){if(!LoadFile(GetDlgItem(hwnd, IDC_MAIN_TEXT), szFileName)){MessageBox(hwnd, "打开文件失败.", "错误信息",MB_OK | MB_ICONEXCLAMATION);return FALSE;}}}return TRUE;}LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) {switch(Message){case WM_CREATE:CreateWindow("EDIT", "",WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL | ES_MULTILINE | ES_WANTRETURN,CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,hwnd, (HMENU)IDC_MAIN_TEXT, g_hInst, NULL);SendDlgItemMessage(hwnd, IDC_MAIN_TEXT, WM_SETFONT,(WPARAM)GetStockObject(DEFAULT_GUI_FONT), MAKELPARAM(TRUE, 0));break;case WM_SIZE:if(wParam != SIZE_MINIMIZED)MoveWindow(GetDlgItem(hwnd, IDC_MAIN_TEXT), 0, 0, LOWORD(lParam),HIWORD(lParam), TRUE);break;case WM_SETFOCUS:SetFocus(GetDlgItem(hwnd, IDC_MAIN_TEXT));break;case WM_COMMAND:switch(LOWORD(wParam)){case CM_FILE_OPEN:DoFileOpenSave(hwnd, FALSE);break;case CM_FILE_SAVEAS:DoFileOpenSave(hwnd, TRUE);break;case CM_FILE_EXIT:PostMessage(hwnd, WM_CLOSE, 0, 0);break;case CM_ABOUT:MessageBox (NULL, "一个Windows C 记事本程序" , "关于...", 0);}break;case WM_CLOSE:DestroyWindow(hwnd);break;case WM_DESTROY:PostQuitMessage(0);break;default:return DefWindowProc(hwnd, Message, wParam, lParam);}return 0;}int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){WNDCLASSEX WndClass;HWND hwnd;MSG Msg;g_hInst = hInstance;WndClass.cbSize = sizeof(WNDCLASSEX);WndClass.style = 0;WndClass.lpfnWndProc = WndProc;WndClass.cbClsExtra = 0;WndClass.cbWndExtra = 0;WndClass.hInstance = g_hInst;WndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); WndClass.hCursor = LoadCursor(NULL, IDC_ARROW); WndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); WndClass.lpszMenuName = "MAINMENU";WndClass.lpszClassName = g_szClassName;WndClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION);if(!RegisterClassEx(&WndClass)){MessageBox(0, "注册窗口失败", "错误信息",MB_ICONEXCLAMATION | MB_OK | MB_SYSTEMMODAL);return 0;}hwnd = CreateWindowEx(WS_EX_CLIENTEDGE,g_szClassName,"一个记事本程序",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT, CW_USEDEFAULT, 800, 600,NULL, NULL, g_hInst, NULL);if(hwnd == NULL){MessageBox(0, "创建窗口失败", "错误信息",MB_ICONEXCLAMATION | MB_OK | MB_SYSTEMMODAL);return 0;}ShowWindow(hwnd, nCmdShow);UpdateWindow(hwnd);while(GetMessage(&Msg, NULL, 0, 0)){TranslateMessage(&Msg);DispatchMessage(&Msg);}return Msg.wParam;}二:编译,连接运行在编译之前需要一个sample.ico图标.打开运行,输入cmd,回车,进入dos命令行进入d:\note下1.用dir命令列一下当前目录包含文件。
记事本程序源代码汇总
记事本程序源代码汇总下面是一个简单的记事本程序的源代码:```#include <iostream>#include <fstream>#include <string>using namespace std;void showMencout << "**********************" << endl; cout << " 记事本程序 " << endl; cout << "**********************" << endl; cout << "请选择以下操作:" << endl;cout << "1. 新建记事本文件" << endl;cout << "2. 打开已有记事本文件" << endl; cout << "3. 查看记事本文件内容" << endl; cout << "4. 添加文本到记事本文件" << endl; cout << "5. 退出程序" << endl;cout << "**********************" << endl; void createFilstring filename;cout << "请输入新建记事本文件的文件名:";cin >> filename;//在当前目录创建一个新文件ofstream outFile(filename);outFile.close(;cout << "成功创建记事本文件:" << filename << endl; void openFilstring filename;cout << "请输入要打开的记事本文件的文件名:";cin >> filename;//尝试打开已存在的文件ifstream inFile(filename);if (!inFile)cout << "无法打开文件:" << filename << endl;} elsestring content;getline(inFile, content, '\0');cout << "记事本文件内容:" << endl;cout << content << endl;inFile.close(;}void viewFilstring filename;cout << "请输入要查看的记事本文件的文件名:"; cin >> filename;//尝试打开已存在的文件ifstream inFile(filename);if (!inFile)cout << "无法打开文件:" << filename << endl; } elsestring line;cout << "记事本文件内容:" << endl;while (getline(inFile, line))cout << line << endl;}inFile.close(;}void appendToFilstring filename;cout << "请输入要添加文本的记事本文件的文件名:";cin >> filename;//尝试打开已存在的文件ofstream outFile(filename, ios::app);if (!outFile)cout << "无法打开文件:" << filename << endl;} elsestring content;cout << "请输入要添加的文本内容(以#结束):" << endl; while (true)getline(cin, content);if (content == "#")break;}outFile << content << endl;}outFile.close(;cout << "成功添加文本到记事本文件:" << filename << endl; }int maiint choice;doshowMenu(;cout << "请输入您的选择:";cin >> choice;switch (choice)case 1:createFile(;break;case 2:openFile(;break;case 3:viewFile(;break;case 4:appendToFile(;break;case 5:cout << "感谢使用记事本程序,再见!" << endl;break;default:cout << "无效的选择,请重新输入!" << endl;}} while (choice != 5);return 0;```这个记事本程序通过命令行界面提供了以下操作:1.新建记事本文件:用户输入一个文件名后,在当前目录下创建一个新文件作为记事本。
记事本源代码(c)
COORD coord = bInfo.dwCursorPosition; //将显存中光标信息赋予coord
*x = coord.X;
*y = coord.Y;
}
{
printf("%c",__strInput[__curStrInput]);
__curStrInput++;
}
else if(__cInput == 27) //EXC退出
{
__curStrInput = 0;
__nLastCur = 0; //字符位数标志
while(1)
{
wherexy(&x,&y); //获得当前光标位置
__cInput = getch();
if(__cInput > 47 && __cInput < 58 && __nLastCur < M && (__cInput != 48 | | __curStrInput != 0))
}
void gotoxy(int x,int y)
{
COORD coord; //windows.h中描述点的结构体
coord.X = x;
coord.Y = y;
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); //获得标准输出设备句柄
gotoxy(x + 1,y);
}
else
{
lse if(__cInput == 13) //回车处理
c语言的记事本源代码txt
;)":)N/Y(入进否是 ;)"n\:作操示提按请 ;)"n\* * * * * * * * * * * * * * * * * * * * * * * * * * * 录讯通:用使迎欢 * * * 丽隋 , 源 宫 : 人 作 制 * ;)"n\* * * * * * * * * * * * * * * * * * * * * * * *
;++i { ))pf(foef!(fi } ;)0(tixe ;)"n\~~~件文开打法无 "(ftnirp { )LLUN==))"+a","txt.ulnuxgnot"(nepof=pf((fi ;0=i :4 esac ;kaerb ;)daeh(sevas ;)daeh(egnahc esle } ;)"~~~回返 请 �录记无中录讯通 "(ftnirp ;)"n\"(ftnirp { )LLUN==daeh(fi
} ;)daeh( nruter ;LLUN=txen>-2p ;1p=2p ;1p=txen>-2p } } ;)brosba&,"c%"(fnacs ;)yfitnedi&,"c%"(fnacs ;)":)N/Y(入输请 "(ftnirp { )'N'=!yfitnedi&&'n'=!yfitnedi&&'Y'=!yfitnedi&&'y'=!yfitnedi(elihw ;)brosba&,"c%"(fnacs ;)yfitnedi&,"c%"(fnacs ;)":)N/Y(�续继否是�存保已容内 "(ftnirp ;)"n\"(ftnirp ;)"n\"(ftnirp ;)rdda>-1p(steg ;)":址地 "(ftnirp ;)let>-1p(steg ;)":话电 "(ftnirp ;)ijnab>-1p(steg ;)":级班 "(ftnirp ;)eman>-1p(steg ;)":名姓 "(ftnirp ;)oaheux>-1p(steg ;)":号学 "(ftnirp ;)"n\"(ftnirp ;)"n\"(ftnirp ;)"n\"(ftnirp ;)"n\"(ftnirp ;)NEL(collam)*knil(=1p ;1p=2p ;1p=txen>-2p { )'Y'==yfitnedi||'y'==yfitnedi(elihw } ;)brosba&,"c%"(fnacs ;)yfitnedi&,"c%"(fnacs ;)":)N/Y(入输请 "(ftnirp { )'N'=!yfitnedi&&'n'=!yfitnedi&&'Y'=!yfitnedi&&'y'=!yfitnedi(elihw ;)brosba&,"c%"(fnacs ;)yfitnedi&,"c%"(fnacs
C#记事本源码
FormMain.csusing System;using System.Collections;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;namespace记事本{public partial class FormMain : Form{public FormMain(){InitializeComponent();//formSearch = new frmSearch();//formSearch.Owner = this; //这样子,查找的窗体就可以找到他了。
}#region文件菜单//判断文件值是否被保存public bool changeNum = false;public string filePath;public void textBox_TextChanged(object sender, EventArgs e) //如果文本发生变化时发生的所有时间{changeNum = true;menuItem1Undo.Enabled = true;menuItem1Cut.Enabled = true;menuItem1Copy.Enabled = true;menuItem1Delet.Enabled = true;///////////////////////// 状态栏//////////////////////////////////////int index = richTextBox.GetFirstCharIndexOfCurrentLine();int line = richTextBox.GetLineFromCharIndex(index) + 1;//行;int Col = richTextBox.SelectionStart - index + 1;toolStripStatusLabel.Text = "第" + line + "行" + Col + "列";///////////////////////// 状态栏//////////////////////////////////////}//新建private void menuItemCreat_Click(object sender, EventArgs e){if (changeNum == true){DialogResult strmsg = MessageBox.Show("是否将记事本保存到 "+ this.Text + "?", "记事本 - 温馨提示", MessageBoxButtons.YesNoCancel);if (strmsg.ToString().Trim() == "Yes") //如果选择了是SaveFileDialog sfd = new SaveFileDialog();if (saveFileDialog.ShowDialog() == DialogResult.OK){FileStream fs =(System.IO.FileStream)saveFileDialog.OpenFile();}}if (strmsg.ToString().Trim() == "No") //如果选择了否{richTextBox.Clear();}if (strmsg.ToString().Trim() == "Cancel") //如果选择了取消 {return;}}else{richTextBox.Clear();}}//打开文件private void menuItemOpen_Click(object sender, EventArgs e){try{if (openFileDialog.ShowDialog() == DialogResult.OK){StreamReader sr = newStreamReader(openFileDialog.FileName);{string line;line = sr.ReadToEnd();this.richTextBox.Text = line;this.Text = openFileDialog.SafeFileName;filePath = openFileDialog.FileName;sr.Close();}this.richTextBox.AppendText("");}catch (Exception ex){MessageBox.Show(ex.Message); //出错时会提示错误信息!}}//保存private void menuItemSave_Click(object sender, EventArgs e){if (filePath != null){File.WriteAllText(filePath, richTextBox.Text); // 保存 }else{SaveFileDialog sfd = new SaveFileDialog();if (saveFileDialog.ShowDialog() == DialogResult.OK){FileStream fs =(System.IO.FileStream)saveFileDialog.OpenFile();}}}//另存为private void menuItemResave_Click(object sender, EventArgs e) {SaveFileDialog sfd = new SaveFileDialog();if (saveFileDialog.ShowDialog() == DialogResult.OK){FileStream fs =(System.IO.FileStream)saveFileDialog.OpenFile();}}//打印private void menuItem1Print_Click(object sender, EventArgs e){StringReader strReader = new StringReader(this.richTextBox.Text);if (printDialog.ShowDialog() == DialogResult.OK)try{printDocument.Print();}catch (Exception ex){MessageBox.Show(ex.Message, "打印错误", MessageBoxButtons.OK, MessageBoxIcon.Error);printDocument.PrintController.OnEndPrint(printDocument, new System.Drawing.Printing.PrintEventArgs());}}//退出private void退出XToolStripMenuItem_Click(object sender, EventArgs e) {if (changeNum == true){DialogResult strmsg = MessageBox.Show("是否将记事本保存到 "+ this.Text + "?", "记事本 - 温馨提示", MessageBoxButtons.YesNoCancel);if (strmsg.ToString().Trim() == "Yes") //如果选择了是{SaveFileDialog sfd = new SaveFileDialog();if (saveFileDialog.ShowDialog() == DialogResult.OK){FileStream fs =(System.IO.FileStream)saveFileDialog.OpenFile();}}if (strmsg.ToString().Trim() == "No") //如果选择了否{this.Close();}if (strmsg.ToString().Trim() == "Cancel") //如果选择了取消 {return;}}elsethis.Close();}#endregion#region编辑//撤销private void menuItem1Undo_Click(object sender, EventArgs e) {if (this.richTextBox.CanUndo == true){richTextBox.Undo();richTextBox.ClearUndo();}}//剪切private void menuItem1Cut_Click(object sender, EventArgs e) {if (this.menuItem1Cut.Enabled == true){Clipboard.SetDataObject(richTextBox.SelectedText);richTextBox.SelectedText = "";}}//复制private void menuItem1Copy_Click(object sender, EventArgs e) {this.richTextBox.Copy();}//粘贴private void menuItem1Past_Click(object sender, EventArgs e) {this.richTextBox.Paste();}//删除private void menuItem1Delet_Click(object sender, EventArgs e) {this.richTextBox.SelectedText = "";}//查找private void menuItemFind_Click(object sender, EventArgs e) {frmSearch formSearch = new frmSearch();formSearch.Init(Search);formSearch.Show();formSearch.Activate();// formSearch.}//全选private void menuItemSelectAll_Click(object sender, EventArgs e) {richTextBox.SelectAll();}//时间日期private void menuItemTime_Click(object sender, EventArgs e){//DateTime date = new DateTime();//richTextBox.Text.Insert(Cursor.Position.X,DateTime.Now.ToString());richTextBox.AppendText(DateTime.Now.ToString());}#endregion#region格式//自动换行private void menuItemEnter_Click(object sender, EventArgs e){if (this.richTextBox.WordWrap == false){this.richTextBox.WordWrap = true;}else{this.richTextBox.WordWrap = false;}}//字体对话框private void menuItemFront_Click(object sender, EventArgs e){if (this.fontDialog.ShowDialog() == DialogResult.OK){richTextBox.Font = fontDialog.Font; //将文本设置成选择的字体。
C#实现简单记事本程序
C#实现简单记事本程序本⽂实例为⼤家分享了使⽤C#写出⼀个简单的记事本程序,供⼤家参考,具体内容如下编程语⾔: C#编程环境: Visual Studio 2013运⾏环境: .NET Framework 4.5预览:功能:标题栏显⽰⽂件标题菜单栏各类菜单命令⽂件- 新建- 打开- 保存- 另存为- 页⾯设置- 打印- 退出编辑 - 撤销- 剪切- 复制- 粘贴- 全选- 时间/⽇期格式 - ⾃动换⾏- 字体视图 - 状态栏- ⼯具栏- 全屏模式帮助- 开源许可- 查看帮助- 关于⼯具栏常⽤⼯具集合标签栏⽂件标签显⽰⼯作区编辑区状态栏显⽰⽂件状态⽂本状态(新建/已修改)字符个数光标坐标功能实现本程序有两个窗体,分别为Form1和AboutBox1所有⽂件如下:对于Form1:需要引⼊的类库:using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;窗体及空间声明代码:private System.Windows.Forms.MenuStrip menuStrip1;private System.Windows.Forms.ToolStripMenuItem ⽂件ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 新建ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 打开ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 保存ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 另存为ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 编辑ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 格式ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 退出ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 关于ToolStripMenuItem;private System.Windows.Forms.TextBox editBox1;private System.Windows.Forms.ToolStripMenuItem 撤销ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 剪切ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 复制ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 粘贴ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 删除ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 全选AToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem ⽇期DToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 格式ToolStripMenuItem1;private System.Windows.Forms.ToolStripMenuItem 字体ToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 查看VToolStripMenuItem;private System.Windows.Forms.ToolStripMenuItem 状态栏ToolStripMenuItem;private System.Windows.Forms.StatusStrip statusStrip1;private System.Windows.Forms.SaveFileDialog saveFileDialog1;private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3;private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4;private System.Windows.Forms.ToolStripMenuItem 页⾯设置UToolStripMenuItem;private System.Drawing.Printing.PrintDocument printDocument1;private System.Windows.Forms.PageSetupDialog pageSetupDialog1;private System.Windows.Forms.ToolStripMenuItem 打印PToolStripMenuItem;private System.Windows.Forms.PrintDialog printDialog1;private System.Windows.Forms.ToolStripMenuItem 查看帮助HToolStripMenuItem;private System.Windows.Forms.ToolStripSeparator toolStripMenuItem5;private System.Windows.Forms.ToolStripMenuItem ⾃动换⾏ToolStripMenuItem;private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;public System.Windows.Forms.Timer timer1;private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel2;private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel3;private System.Windows.Forms.ToolStripMenuItem 全屏模式ToolStripMenuItem;private System.Windows.Forms.ToolStrip toolStrip1;private System.Windows.Forms.ToolStripButton newButton;private System.Windows.Forms.ToolStripButton openButton;private System.Windows.Forms.ToolStripButton saveButton;private System.Windows.Forms.ToolStripButton saveAsButton;private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;private System.Windows.Forms.ToolStripButton cutButton;private System.Windows.Forms.ToolStripButton copyButton;private System.Windows.Forms.ToolStripButton pasteButton;private System.Windows.Forms.ToolStripButton deleteButton;private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;private System.Windows.Forms.ToolStripButton timeButton;private System.Windows.Forms.ToolStripButton fullButton;private System.Windows.Forms.ToolStripButton textButton;private System.Windows.Forms.ToolStripMenuItem ⼯具栏ToolStripMenuItem;private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel4;private System.Windows.Forms.ToolStripMenuItem 开源许可OToolStripMenuItem;private System.Windows.Forms.TabControl tabControl1;private System.Windows.Forms.TabPage tabPage1;private System.Windows.Forms.TabPage tabPage2;private System.Windows.Forms.TextBox editBox2;1窗体载⼊:private void Form1_Load(object sender, EventArgs e){this.editBox1.ScrollBars = ScrollBars.Both;this.editBox2.ScrollBars = ScrollBars.Both;this.Text = textFileName + " - " + programeName;//显⽰⽂件名this.timer1.Start();editBox1.Focus();}⾸先进⾏⼀些固定变量声明:private string textFileName = "⽆标题";private string programeName = "Icey";private string filePath = "";private string asFilePath = "";private string selecteText = "";private string helpUrl = "https:///icey";private string openSourceUrl = "https:///mayuko2012/icey";private string wrongMessage = "你好像遇到了错误...";private string fileFormat = "⽂本⽂件(*.txt)|*.txt|Icey⽂件(*.ice)|*.ice|C++⽂件(*.cpp)|*.cpp|C⽂件(*.c)|*.c|所有⽂件(*.*)|(*.*)"; private string tabFileName1 = "⽆标题1 - Icey";private string tabFileName2 = "⽆标题2 - Icey";Boolean saveFileStatus1 = false;Boolean textChanged1 = false;Boolean saveFileStatus2 = false;Boolean textChanged2 = false;private void saveFile()//保存{if (!textFileName.Equals("")){SaveFileDialog saveFile = new SaveFileDialog();saveFile.Filter = fileFormat;saveFile.FileName = "*.txt";if (saveFile.ShowDialog() == DialogResult.OK){filePath = saveFile.FileName;StreamWriter sw = new StreamWriter(filePath, false, Encoding.Default);sw.Write((editBox1.Focused) ? editBox1.Text : editBox2.Text);sw.Close();if (editBox1.Focused){tabFileName1 = saveFile.FileName + " - " + programeName;saveFileStatus1 = true;}else if (editBox2.Focused){tabFileName2 = saveFile.FileName + " - " + programeName;saveFileStatus2 = true;}}}toolStripStatusLabel4.Text = "已保存";}另存为采⽤函数形式:private void saveAsFile()//另存为{SaveFileDialog saveAsFile = new SaveFileDialog();saveAsFile.Filter = fileFormat;saveAsFile.FileName = "*.txt";if (saveAsFile.ShowDialog() == DialogResult.OK){asFilePath = saveAsFile.FileName;StreamWriter sw = new StreamWriter(asFilePath, false, Encoding.Default);sw.WriteLine((editBox1.Focused) ? editBox1.Text : editBox2.Text);sw.Close();FileInfo fileInfo = new FileInfo(saveAsFile.FileName);textFileName = ;}toolStripStatusLabel4.Text = "已保存";}新建函数:private void newFile()//新建{if (editBox1.Focused){if (editBox1.Text != String.Empty && saveFileStatus1 == false && textChanged1 == true)//如果⽂本框不为空{DialogResult result = MessageBox.Show("是否将窗⼝1已编辑⽂件保存到 " + textFileName, wrongMessage, MessageBoxButtons.YesNoCancel, rmation); if (result == DialogResult.Yes){saveFile();Application.Exit();}else if (result == DialogResult.No){editBox1.Text = "";}}elseeditBox1.Text = "";}else if (editBox2.Focused){if (editBox2.Text != String.Empty && saveFileStatus2 == false && textChanged2 == true)//如果⽂本框不为空{DialogResult result = MessageBox.Show("是否将窗⼝2已编辑⽂件保存到 " + textFileName, wrongMessage, MessageBoxButtons.YesNoCancel, rmation); if (result == DialogResult.Yes){saveFile();Application.Exit();}else if (result == DialogResult.No){editBox2.Text = "";}}elseeditBox2.Text = "";}}打开⽂件函数:private void openFile()//打开OpenFileDialog openFile = new OpenFileDialog();openFile.Filter = fileFormat;if (openFile.ShowDialog() == DialogResult.OK){StreamReader sr = new StreamReader(openFile.FileName, Encoding.Default);if (editBox1.Focused){editBox1.Text = sr.ReadToEnd();}else if(editBox2.Focused){editBox2.Text = sr.ReadToEnd();}sr.Close();FileInfo fileInfo = new FileInfo(openFile.FileName);if (editBox1.Focused){tabFileName1 = + " - " + programeName;saveFileStatus1 = true;}else if (editBox2.Focused){tabFileName2 = + " - " + programeName;saveFileStatus2 = true;}textFileName = ;}}全屏模式函数:private void fullScreen()//全屏{if (全屏模式ToolStripMenuItem.Checked == false){this.WindowState = FormWindowState.Maximized;全屏模式ToolStripMenuItem.Checked = true;this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;}else{this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;this.WindowState = FormWindowState.Normal;全屏模式ToolStripMenuItem.Checked = false;}}退出菜单命令:private void 退出ToolStripMenuItem_Click(object sender, EventArgs e){if (editBox1.Text != String.Empty || saveFileStatus1 == false && textChanged1 == true){this.tabPage1.Show();this.editBox1.Focus();DialogResult result = MessageBox.Show("是否将窗⼝1已编辑⽂件保存到 " + textFileName, wrongMessage, MessageBoxButtons.YesNoCancel, rmation); if (result == DialogResult.Yes){saveFile();Application.Exit();}else if (result == DialogResult.No){Application.Exit();}}else if (editBox2.Text != String.Empty || saveFileStatus2 == false && textChanged2 == true){this.tabPage2.Show();this.editBox2.Focus();DialogResult result = MessageBox.Show("是否将窗⼝2已编辑⽂件保存到 " + textFileName, wrongMessage, MessageBoxButtons.YesNoCancel, rmation); if (result == DialogResult.Yes){saveFile();Application.Exit();}else if (result == DialogResult.No){Application.Exit();}}elseApplication.Exit();}Bool变量,⽤于判断TextBox是否发⽣变化:private void textBox1_TextChanged(object sender, EventArgs e){textChanged2 = true;toolStripStatusLabel4.Text = "已修改";}private void editBox2_TextChanged(object sender, EventArgs e)textChanged2 = true;toolStripStatusLabel4.Text = "已修改";}新建菜单命令:private void 新建ToolStripMenuItem_Click(object sender, EventArgs e){newFile();}打开菜单命令:private void 打开ToolStripMenuItem_Click(object sender, EventArgs e){openFile();}字体菜单命令:private void 字体ToolStripMenuItem_Click(object sender, EventArgs e){FontDialog fontDialog = new FontDialog();if (fontDialog.ShowDialog() == DialogResult.OK){if (editBox1.Focused){editBox1.Font = fontDialog.Font;}elseeditBox2.Font = fontDialog.Font;}}退出动作(当⽤户点击窗体右上⾓退出按钮时执⾏此操作):private void Form1_FormClosing(object sender, FormClosingEventArgs e){if (editBox1.Text != String.Empty && e.CloseReason == erClosing || saveFileStatus1 == false && textChanged1 == true)//如果⽂本框不为空&&触发关闭按钮事件{this.tabPage1.Show();this.editBox1.Focus();DialogResult result = MessageBox.Show("是否将窗体1已编辑⽂件保存到 " + textFileName, wrongMessage, MessageBoxButtons.YesNoCancel, rmation);if (result == DialogResult.Yes){saveFile();e.Cancel = false;}else if (result == DialogResult.No){e.Cancel = false;}else if (result == DialogResult.Cancel){e.Cancel = true;}}else if (editBox2.Text != String.Empty && e.CloseReason == erClosing || saveFileStatus2 == false && textChanged2 == true)//如果⽂本框不为空&&触发关闭按钮事件 {this.tabPage2.Show();this.editBox2.Focus();DialogResult result = MessageBox.Show("是否将窗⼝2已编辑⽂件保存到 " + textFileName, wrongMessage, MessageBoxButtons.YesNoCancel, rmation);if (result == DialogResult.Yes){saveFile();e.Cancel = false;}else if (result == DialogResult.No){e.Cancel = false;}else if (result == DialogResult.Cancel){e.Cancel = true;}}elseApplication.Exit();}状态栏命令(状态栏是否显⽰):private void 状态栏ToolStripMenuItem_Click(object sender, EventArgs e){if (状态栏ToolStripMenuItem.Checked == true){状态栏ToolStripMenuItem.Checked = false;statusStrip1.Visible = false;}else{状态栏ToolStripMenuItem.Checked = true;statusStrip1.Visible = true;}编辑命令:private void 编辑ToolStripMenuItem_Click(object sender, EventArgs e) {if ((editBox1.SelectedText.Equals(""))){剪切ToolStripMenuItem.Enabled = false;复制ToolStripMenuItem.Enabled = false;删除ToolStripMenuItem.Enabled = false;}else{剪切ToolStripMenuItem.Enabled = true;复制ToolStripMenuItem.Enabled = true;删除ToolStripMenuItem.Enabled = true;}}全选命令:private void 全选AToolStripMenuItem_Click(object sender, EventArgs e) {if (editBox1.Focused){this.editBox1.SelectAll();}elsethis.editBox2.SelectAll();}剪切复制粘贴删除命令:private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e) {if (editBox1.Focused){selecteText = editBox1.SelectedText;this.editBox1.Cut();}else{selecteText = editBox2.SelectedText;this.editBox2.Cut();}}private void 撤销ToolStripMenuItem_Click(object sender, EventArgs e) {if (editBox1.Focused){this.editBox1.Undo();}elsethis.editBox2.Undo();}private void 复制ToolStripMenuItem_Click(object sender, EventArgs e) {if (editBox1.Focused){this.editBox1.Copy();}elsethis.editBox2.Copy();}private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e) {if (editBox1.Focused){this.editBox1.Paste();}elsethis.editBox2.Paste();}private void 删除ToolStripMenuItem_Click(object sender, EventArgs e) {if (editBox1.Focused){this.editBox1.SelectedText = "";}elsethis.editBox2.SelectedText = "";}保存命令:private void 保存ToolStripMenuItem_Click(object sender, EventArgs e) {saveFile();}private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e){saveAsFile();}时间戳命令:private void ⽇期DToolStripMenuItem_Click(object sender, EventArgs e){if (editBox1.Focused){editBox1.AppendText(System.DateTime.Now.ToString());}elseeditBox2.AppendText(System.DateTime.Now.ToString());}页⾯设置命令:private void 页⾯设置UToolStripMenuItem_Click(object sender, EventArgs e){pageSetupDialog1.Document = printDocument1;this.pageSetupDialog1.AllowMargins = true;this.pageSetupDialog1.AllowOrientation = true;this.pageSetupDialog1.AllowPaper = true;this.pageSetupDialog1.AllowPrinter = true;this.pageSetupDialog1.Document = this.printDocument1;pageSetupDialog1.ShowDialog();}打印命令:private void 打印PToolStripMenuItem_Click(object sender, EventArgs e){this.printDialog1.Document = this.printDocument1;this.printDialog1.PrinterSettings = this.pageSetupDialog1.PrinterSettings;if (this.printDialog1.ShowDialog() == DialogResult.OK){try{this.printDocument1.Print();}catch (Exception ex){MessageBox.Show(ex.Message, wrongMessage, MessageBoxButtons.OK, MessageBoxIcon.Error);}}}查看帮助关于命令:private void 查看帮助HToolStripMenuItem_Click(object sender, EventArgs e){System.Diagnostics.Process.Start(helpUrl);}private void 关于ToolStripMenuItem_Click(object sender, EventArgs e){AboutBox1 about = new AboutBox1();about.StartPosition = FormStartPosition.CenterScreen;about.Show();about.Owner = this;//timer1.Stop();}⾃动换⾏命令:private void ⾃动换⾏ToolStripMenuItem_Click(object sender, EventArgs e){if (⾃动换⾏ToolStripMenuItem.Checked == true){editBox1.WordWrap = false;editBox2.WordWrap = false;⾃动换⾏ToolStripMenuItem.Checked = false;}else{editBox1.WordWrap = true;editBox2.WordWrap = true;⾃动换⾏ToolStripMenuItem.Checked = true;}}计时器(100 ms刷新频率):private void timer1_Tick(object sender, EventArgs e){toolStripStatusLabel1.Text = (editBox1.Focused) ? editBox1.Text.Length.ToString() + " 个字符" : editBox2.Text.Length.ToString() + " 个字符";int totalline = (editBox1.Focused) ? editBox1.GetLineFromCharIndex(editBox1.Text.Length) + 1 : editBox2.GetLineFromCharIndex(editBox2.Text.Length) + 1;//得到总⾏数int index = (editBox1.Focused) ? editBox1.GetFirstCharIndexOfCurrentLine() : editBox2.GetFirstCharIndexOfCurrentLine();//得到当前⾏第⼀个字符的索引int line = (editBox1.Focused) ? editBox1.GetLineFromCharIndex(index) + 1 : editBox2.GetLineFromCharIndex(index) + 1;//得到当前⾏的⾏号int col = (editBox1.Focused) ? editBox1.SelectionStart - index + 1 : editBox2.SelectionStart - index + 1;//.SelectionStart得到光标所在位置的索引 - 当前⾏第⼀个字符的索引 = 光标所在的列数 toolStripStatusLabel2.Text = "第" + line + "⾏,第" + col + "列";cutButton.Enabled = false;copyButton.Enabled = false;deleteButton.Enabled = false;}else{cutButton.Enabled = true;copyButton.Enabled = true;deleteButton.Enabled = true;}if (editBox1.Focused){editBox1.Focus();this.Text = tabFileName1;}else{editBox2.Focus();this.Text = tabFileName2;}if (editBox2.Focused){editBox2.Focus();this.Text = tabFileName2;}else{editBox1.Focus();this.Text = tabFileName1;}}⼯具栏命令(⼯具栏是否显⽰):private void ⼯具栏ToolStripMenuItem_Click(object sender, EventArgs e){if (⼯具栏ToolStripMenuItem.Checked == false){toolStrip1.Visible = true;⼯具栏ToolStripMenuItem.Checked = true;}else if(⼯具栏ToolStripMenuItem.Checked == true){toolStrip1.Visible = false;⼯具栏ToolStripMenuItem.Checked = false;}}开源许可命令:private void 开源许可OToolStripMenuItem_Click(object sender, EventArgs e) {System.Diagnostics.Process.Start(openSourceUrl);}⼯具栏的各个按钮:private void newButton_Click(object sender, EventArgs e){newFile();}private void openButton_Click(object sender, EventArgs e){openFile();}private void saveButton_Click(object sender, EventArgs e){saveFile();}private void saveAsButton_Click(object sender, EventArgs e){saveAsFile();}private void cutButton_Click(object sender, EventArgs e){if (editBox1.Focused){selecteText = editBox1.SelectedText;this.editBox1.Cut();}else{selecteText = editBox2.SelectedText;this.editBox2.Cut();}}private void copyButton_Click(object sender, EventArgs e){if (editBox1.Focused)this.editBox1.Copy();}elsethis.editBox2.Copy();}private void pasteButton_Click(object sender, EventArgs e) {if (editBox1.Focused){this.editBox1.Paste();}elsethis.editBox2.Paste();}private void deleteButton_Click(object sender, EventArgs e) {if (editBox1.Focused){this.editBox1.SelectedText = "";}elsethis.editBox2.SelectedText = "";}private void timeButton_Click(object sender, EventArgs e) {if (editBox1.Focused){editBox1.AppendText(System.DateTime.Now.ToString()); }elseeditBox2.AppendText(System.DateTime.Now.ToString()); }private void textButton_Click(object sender, EventArgs e) {FontDialog fontDialog = new FontDialog();if (fontDialog.ShowDialog() == DialogResult.OK){if (editBox1.Focused){editBox1.Font = fontDialog.Font;}elseeditBox2.Font = fontDialog.Font;}}private void fullButton_Click(object sender, EventArgs e) {fullScreen();}标签栏:private void tabPage1_Click(object sender, EventArgs e){editBox1.Focus();this.Text = tabPage1.Text;if (textChanged1 == false){toolStripStatusLabel4.Text = "新建";}}private void tabPage2_Click(object sender, EventArgs e) {editBox2.Focus();this.Text = tabPage2.Text;if (textChanged2 == false){toolStripStatusLabel4.Text = "新建";}}对于AboutBox:using System;using System.Collections.Generic;using ponentModel;using System.Drawing;using System.Linq;using System.Reflection;using System.Threading.Tasks;using System.Windows.Forms;namespace Notepad{partial class AboutBox1 : Form{public AboutBox1(){this.Text = String.Format("关于 {0}", AssemblyTitle);belProductName.Text = AssemblyProduct;belVersion.Text = String.Format("版本 {0}", AssemblyVersion);belCopyright.Text = AssemblyCopyright;belCompanyName.Text = AssemblyCompany;this.textBoxDescription.Text = AssemblyDescription;}#region 程序集特性访问器public string AssemblyTitle{get{object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);if (attributes.Length > 0){AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];if (titleAttribute.Title != ""){return titleAttribute.Title;}}return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);}}public string AssemblyVersion{get{return Assembly.GetExecutingAssembly().GetName().Version.ToString();}}public string AssemblyDescription{get{object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); if (attributes.Length == 0){return "";}return ((AssemblyDescriptionAttribute)attributes[0]).Description;}}public string AssemblyProduct{get{object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);if (attributes.Length == 0){return "";}return ((AssemblyProductAttribute)attributes[0]).Product;}}public string AssemblyCopyright{get{object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (attributes.Length == 0){return "";}return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;}}public string AssemblyCompany{get{object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); if (attributes.Length == 0){return "";}return ((AssemblyCompanyAttribute)attributes[0]).Company;}}#endregionprivate void AboutBox1_Load(object sender, EventArgs e){}private void okButton_Click(object sender, EventArgs e)}private void AboutBox1_FormClosing(object sender, FormClosingEventArgs e){Form1 frm1 = (Form1)this.Owner;frm1.timer1.Start();}}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
result = MessageBox.Show("文件 " + this.Text + " 的文字已经改变。\r\n\r\n想保存文件吗?", "记事本", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
}
else
e.Cancel = true;
}
}
catch { }
richTextBox1.Text = "";
}
else
{
e.Cancel = true;
{
richTextBox1.Text = "";
rtb = richTextBox1.Text;
}
}
private Point GetCursorPos(RichTextBox richtextBox)
{
Point cursorPos = new Point(0, 0);
int x, y;
y = SendMessage(richtextBox.Handle, EM_LINEFROMCHAR, richtextBox.SelectionStart, 0);
using System;
using System.Collections.Generic;
using ponentModel;
using System.Data;
using System.Drawing;
usinቤተ መጻሕፍቲ ባይዱ System.Text;
using System.Windows.Forms;
if (result == DialogResult.Yes)
{
saveFileDialog1.Filter = @"文本文档(*.txt)|*.txt|所有格式|*.txt;*.doc;*.cs;*.rtf;*.sln";
public string rtb="";
public Form1()
{
InitializeComponent();
}
[System.Runtime.InteropServices.DllImport("User32.DLL")]
if (saveFileDialog1.ShowDialog() == DialogResult.Yes)
{
richTextBox1.SaveFile(saveFileDialog1.FileName.ToString(), RichTextBoxStreamType.PlainText);
d = 1;
saveFileDialog1.FileName = "*.txt";
openFileDialog1.FileName = "*.txt";
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
openFileDialog1.FileName = "*.txt";
DialogResult result;
try
{
if (rtb != richTextBox1.Text)
richTextBox1.Text = "";
rtb = richTextBox1.Text;
}
else if (result == DialogResult.No)
public int k = 0;
public int j = 0;
public int b = 0;
public int c = 0;
public int d = 0;
public int f = 0;
{
if (rtb != richTextBox1.Text)
{
result = MessageBox.Show("文件 " + this.Text + " 的文字已经改变。\r\n\r\n想保存文件吗?", "记事本", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
}
private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result;
try
x = richtextBox.SelectionStart - SendMessage(richtextBox.Handle, EM_LINEINDEX, y, 0);
cursorPos.Y = ++y;
cursorPos.X = ++x;
using System.IO;
using System.Diagnostics;
namespace 文本文档
{
public partial class Form1 : Form
{
public int a = 0;
public int i = -1;
}
}
catch { }
撤消UToolStripMenuItem.Enabled = false;
撤消ToolStripMenuItem.Enabled = false;
return cursorPos;
}
private void Form1_Load(object sender, EventArgs e)
{
自动换行WToolStripMenuItem.Checked = false;
saveFileDialog1.ShowDialog();
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
if (result == DialogResult.Yes)
{
saveFileDialog1.Filter = @"文本文档(*.txt)|*.txt|所有格式|*.txt;*.doc;*.cs;*.rtf;*.sln";
}
private void 新建ToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.FileName = "*.txt";
else
{
richTextBox1.Text = "";
rtb = richTextBox1.Text;
this.Text = "无标题-记事本";
saveFileDialog1.ShowDialog();
if (result == DialogResult.Yes)
{
saveFileDialog1.Filter = @"文本文档(*.txt)|*.txt|所有格式|*.txt;*.doc;*.cs;*.rtf;*.sln";
{
DialogResult result;
try
{
if (rtb != richTextBox1 .Text)
{
result = MessageBox.Show("文件 " +this.Text + " 的文字已经改变。\r\n\r\n想保存文件吗?", "记事本", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
}
}
else if (result == DialogResult.No)
{
this.Dispose();
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int iParam);
private const int EM_LINEFROMCHAR = 0xC9;
private const int EM_LINEINDEX = 0xBB;