新手学C++/CLI及C#

  • 程序结构
  • C++/CLI风格(此代码大部分由系统生成)

#pragma once

///声明命名空间

namespace Form1 {

    /////////////////引入命名空间

       using namespace System;

       using namespace System::ComponentModel;

       using namespace System::Collections;

       using namespace System::Windows::Forms;

       using namespace System::Data;

       using namespace System::Drawing;

    /////////////////////////////////

       /// <summary>

       /// Form1 摘要

       /// </summary>

       public ref class Form1 : public System::Windows::Forms::Form        //声明类(CLR)

       {

       public:

              Form1(void)

              {

                     InitializeComponent();

                     //

                     //TODO: 在此处添加构造函数代码

                     //

              }

 

       protected:

              /// <summary>

              /// 清理所有正在使用的资源

              /// </summary>

              ~Form1()

              {

                     if (components)

                     {

                            delete components;

                     }

              }

 

       private:

              /// <summary>

              /// 必需的设计器变量

              /// </summary>

              System::ComponentModel::Container ^components;

 

//////////////////控件属性描述

#pragma region Windows Form Designer generated code

              /// <summary>

              /// 设计器支持所需的方法不要

              /// 使用代码编辑器修改此方法的内容

              /// </summary>

              void InitializeComponent(void)

              {

                     this->SuspendLayout();

                     //

                     // Form1

                     //

                     this->AutoScaleDimensions = System::Drawing::SizeF(6, 12);

                     this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;

                     this->ClientSize = System::Drawing::Size(284, 262);

                     this->Name = L"Form1";

                     this->Text = L"Form1";

                     this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);

                     this->ResumeLayout(false);

 

              }

///////////////////////////////////////////////////

 

#pragma endregion

       private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

                            //添加事件代码

                      }

       };

}

 

 

  • C#风格

///////////////导入命名空间

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;           

///////////////////

 

///////////声明命名空间

namespace WindowsFormsApplication1

{

public partial class Form1 : Form         ///声明类(分部类)

    {

        string address;    //定义公共变量

        public Form1()

        {

            InitializeComponent();

            address = Environment.CurrentDirectory;    //初始化公共变量

        }

 

        private void Form1_Load(object sender, EventArgs e)      //事件代码?

        {

 

        }

    }

}

 

 

 

 

  • 控件(类)、方法、属性、事件
  • 常用Form控件及其专有属性

 控件

专有属性方法事件 

Form

StartPosition(窗体初现位置)  IsMdiContainer(是否为MDI父窗体)  MdiParent(MDI父窗体)  MdiChild(MDI子窗体)    AcceptButtons(窗体接受按钮)  Opaciaty(透明度)

Controls->Add()    Close   

Load    Activated

TextBox类

ReadOnly(只读)   WordWrap(自动换行)   SelectionFont(选中文本字体)   SelectionLength (选中文本长度) TextLength(所有文本长度)   CanSelect(能否选中控件)   CanUndo(能否撤销)  CanRedo(能否恢复)

Clear()(新建)   Cut()(剪切)    Copy()(复制)    Paste()(粘贴)   Find()(查找)   Select()(选择文本)   SelectAll()(全选)   Undo()(撤销)   Redo()(恢复)   

TextChange(Text属性改变)

MenuStrip

&ContextMenuStrip

Checked(能否复选)   ShortCutKeys (快捷键)

OpenFileDialog

&SaveFileDialog

DefaultExt(默认文件格式)   RestoreDirectory(保存上次目录)

InitialDirectory(初始目录)   MultiSelect(能否选择多个文件)

PrintDialog

&PrintDocument

&PrintPreviewControl

&PrintPreviewDialog

&PageSetupDialog

Document(文档)    AllowPrintToFile(打印到文件)   ShowNetwork(显示网络)     AllowPrinter(启用和禁用打印机选择)       AllowPaper(启用和禁用纸张选择)

FontDialog

&ColorDialog

AllowFullOpen(启用和禁用自定义颜色)   ShowApply(显示“应用”)

ShowColor(显示颜色选项)   ShowEffects(显示 加粗、倾斜等选项)

(Link)Label & Button

FlatStyle(外观)

Timer

Interval(时钟周期)    Tick

其他控件

RadioButton(单选框)  &  CheckBox(复选框)  &  ScrollBar(滚动条)  &  TabControl(选项卡)  &  NotifyIcon(托盘图标)    &  PictureBox(图形框)  &  ProgessBar(进度条)

 

 

  • Form公共属性、方法、事件

公共属性

Name(名称)  Dock(停靠)  Anchor(锚定)   Location(位置)  Size(大小)   BackColor(背景颜色) ForeColor(前景颜色)   Font(字体)   Text(显示文本)   TextAlign(文本对齐方式)     (Form)BorderStyle(边框样式)   TabIndex(Tab键顺序)  Enabled(可用性)  Visible(可见性)  Cursor(鼠标样式)   CanFocus (能否接受输入焦点)    AutoSize(自动调整大小)  Locked(锁定控件)    AllowDrop(能否接受鼠标拖到上面的数据)    Image(背景图像)

公共方法

DateTime::Now(获取系统时间)        MessageBox::Show()(显示对话框)    Focus()(获取输入焦点)   ToString()(转换为字符串)  ToInt()(转换为整型)    ToBoolean() (转换为布尔型)

公共事件

Click(点击)    MouseDown(按下鼠标键)    MouseUp(释放鼠标键)   KeyPress(按下并释放键)

 

 

 

 

  • 语法

由于C++/CLI语法与C#差别极小,故此处语法以C++/CLI为主。

  1. 1.     变量类型

C++/CLI 和C#的类型分为  值类型、引用类型和指针类型,值类型和指针类型想必大家都有了解。引用类型包含对象(Object)、字符串(String)和数组(array)类型。

在C++/CLI中声明引用类型时必须在数据类型右侧角括号加上追踪句柄 “^”,实例化对象时必须必须使用gcnew运算符,且在对象名左侧加上追踪句柄”^”。此外通过对象访问成员,必须利用”->”访问。(CLR)

而在C#中声明类型一律不使用追踪句柄”^”,实例化对象全部使用new运算符。访问成员则一律利用”.”运算符。由于.NET的共通性,其属性、方法和事件与C++/CLI基本一致。

由于C++/CLI语句改到C# 较易,故下文无特别声明则全部使用C++/CLI风格语法。

 

  1. 2.     声明类型

Form^ About=gcnew Form();           //声明一个窗体

TextBox^ txtFind=gcnew TextBox();               //声明一个文本框

String ^str1,^str2;            //声明两个字符串

 

  1. 3.     声明数组 控件数组

array<int>^ index=gcnew array<int>(5,8);           //二维整型数组

array<String^>^ str=gcnew array<String^>(8);          //字符串数组

array<Label^>^ lblMine=gcnew array<Label^>(256);          //控件数组

想必初始化大家都会,当然是使用 for 循环。

 

 

  1. 4.     控件属性描述语法

menuStrip->Location = System::Drawing::Point(0, 0);      //定义位置

menuStrip->Size = System::Drawing::Size(344, 25);         //定义大小

btnMine[i]->Font=(gcnew System::Drawing::Font(L"微软雅黑", 10.5F, FontStyle::Regular, GraphicsUnit::Point,static_cast<System::Byte>(134)));           //定义字体

btnMine[index]->BackColor=System::Drawing::SystemColors::MenuHighlight;  

//定义系统颜色

btnMine[index]->BackColor=System::Drawing::Color::Red;         //定义颜色

 

  1. 5.     关键语句

有些语句感觉就像与人打招呼一样,没有多大的创新可以再被提出,大家更多的是模仿。我觉得对于这些代码只需要理解并记住就行了,不必研究那么透彻,但又很常用,不得不管。故列下一些来,以备以后改用。

 

打开文档

String^ ptrfile;             //用来存储文件地址和文件名

……

    dlgOpenFile->Filter="文本文档(*.txt)|*.txt|程序文件(*.c,*.cpp,*.h,*.cs,*.xml)|*.c;*.cpp;*.h;*.cs,*.xml| 所有文件 (*.*)|*.*";

       dlgOpenFile->DefaultExt="*.txt";

       dlgOpenFile->FileName="";

       dlgOpenFile->RestoreDirectory=true;

       if(dlgOpenFile->ShowDialog()==System::Windows::Forms::DialogResult::OK){

              ptrfile=dlgOpenFile->FileName;

              rtbShow->LoadFile(ptrfile,RichTextBoxStreamType::PlainText);

              this->Text=String::Concat(ptrfile,"-NotePad");          //更换标题栏标题

       }

 

 

保存文档

if(ptrfile==nullptr){

       tsmSaveAs_Click(sender,e);           //调用另存为

       return;

}

else{

       System::IO::StreamWriter^ sw=gcnew System::IO::StreamWriter(ptrfile,false,System::Text::Encoding::Default);

       sw->Write(rtbShow->Text);

       sw->Close();

}

 

打印

dlgPrint->Document=Document;     //Document为PrintDocument实例化对象

if(dlgPrint->ShowDialog()==System::Windows::Forms::DialogResult::OK){

       Document->Print();

}

 

Document部分代码存在着业已知晓的Bug,大家用用就知道了

 

System::Drawing::Font^ PrintFont=gcnew System::Drawing::Font(rtbShow->Font->ToString(),15,System::Drawing::FontStyle::Regular); e->Graphics->DrawString(rtbShow->Text,PrintFont,System::Drawing::Brushes::Black,15,dlgPageSetup->PageSettings->Landscape);

 

剪切

if(!rtbShow->SelectedText->Equals("")){

       rtbShow->Cut();

       IDataObject^ buff2=Clipboard::GetDataObject();

}

 

复制

rtbShow->Copy();

 

粘贴

if(Clipboard::GetDataObject()->GetDataPresent(DataFormats::Text)==true){

       rtbShow->Paste();

}

 

字体

dlgFont->ShowColor=true;

dlgFont->Font=rtbShow->SelectionFont;

dlgFont->Color=rtbShow->SelectionColor;

if(dlgFont->ShowDialog()==System::Windows::Forms::DialogResult::OK){

        rtbShow->SelectionFont=dlgFont->Font;

        rtbShow->SelectionColor=dlgFont->Color;

}

 

 

  1. 6.     与新添加项的联动

在C++/CLI中此项内容至今未取得突破,也请高手指点

反倒是在C#成功实现了部分此功能,却未能成功调用父窗体的方法

下面是我在C#记事本中调用关于窗口的语句,About是新加的Form类。

Form  fomAbout = new About ();   ///此处也可写为 About  fomAbout = new About (); 

fomAbout.Show();

 

 

  1. 7.      事件 EventArgs MouseEventArgs
  2. //添加Click事件

this->tsmNew->Click += gcnew System::EventHandler(this, &Form1::tsmNew_Click);

 

//添加MouseUp事件,MouseDown事件同理

btnMine[i]->MouseUp+=gcnew System::Windows::Forms::MouseEventHandler(this,&Form1::Mine_MouseUp);

 

//添加Load事件

this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);

 

 

//Mine_Click事件代码

private: System::Void Mine_Click(System::Object^ sender, System::Windows::Forms:: EventArgs^ e) {

               //添加事件代码

}

 

//Mine_MouseUp事件代码

private: System::Void Mine_MouseUp(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {

               //添加事件代码

}

 

//Form1_Load事件代码

private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

              //添加事件代码                                        

}

 

外:前瞻

Windows Vista及 Win 7的普及使得微软的WPF成为之后Windows平台软件界面(UI)开发的必备利器。而新的平台意味着新的学习,WPF中的控件和属性与Win Form 相去甚远。很多东西我们都不得不重新学习……而针对API以及各种Web服务统一化的WCF同样展现出巨大的潜力和能力,配合WPF一定很强大。但是,没有一定的基础很难理解WCF中的概念。我看过很长时间的WCF,可先有收获。

现在伴随着网络的发展,Web服务已经无处不在。很多单机的软件已经 开始向网络迁移,网络软件同样表现出强大的生命力和潜力。而且相比单机软件,网络服务利润率更高,商机更大,盗版更难。我们就更要学好WCF以及ASP,还有HTTP语言。

当然,不管要做以上哪个,只要稍大些的软件(Application),都少不了数据库。所以,MS的易上手的SQL就摆在了我们的面前……

知识共享许可协议
作品Wave创作,采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
原文地址:https://www.cnblogs.com/sanwave/p/2015545.html