Microsoft SpecificThis section describes the C/C++ language-level features supporting the Streaming SIMD Extensions 2 (SSE2) instructions:
Floating-Point Intrinsics Using Streaming SIMD Extensions 2 Instructions that describe the intrinsic operations for the double-precision, floating-point data type (__m128d).
Integer Intrinsics Using Streaming SIMD Extensions 2 that describe the intrinsics for the extended-precision integer data type (__m128i).
Other topics discussed in this section include:
Floating-Point Memory and Initialization Operations Using Streaming SIMD Extensions 2
Cache Support for Streaming SIMD Extensions 2 Floating-Point Operations
Integer Memory and Initialization Using Streaming SIMD Extensions 2
Cache Support for Streaming SIMD Extensions 2 Integer Operations
Macro Function for Shuffle Using Streaming SIMD Extensions 2
The emmintrin.h header file contains the declarations for the SSE2 instructions intrinsics. The file dvec.h contains operator overloads for some of the SSE2 instructions intrinsics, which are available for use in C++ programs.
SSE2 intrinsics use the __m128, __m128i, and __m128d data types, which are not supported on Itanium Processor Family (IPF) processors. Any SSE2 intrinsics that use the __m64 data type are not supported on x64 processors.
END Microsoft Specific
Streaming SIMD Extensions (SSE)
Microsoft SpecificThis section describes the C/C++ language-level features supporting SSE. The following features of the intrinsics are explained:
Streaming SIMD Extensions Supported by 3DNow!
Floating-Point Intrinsics Using Streaming SIMD Extensions
Miscellaneous Intrinsics Using Streaming SIMD Extensions
Memory and Initialization Using Streaming SIMD Extensions
Integer Intrinsics Using Streaming SIMD Extensions
Cache Support Using Streaming SIMD Extensions
In addition, the following macro functions are described:
Macro Function for Shuffle Using Streaming SIMD Extensions
Macro Functions to Read and Write the Control Registers
Macro Function for Matrix Transposition
The header file xmmintrin.h contains the declarations for the SSE intrinsics. The file fvec.h contains operator overloads for some of the SSE intrinsics, which are available for use in C++ programs.
SSE intrinsics use the __m128, __m128i, and __m128d data types, which are not supported on Itanium Processor Family (IPF) processors. Any SSE intrinsics that use the __m64 data type are not supported on x64 processors.
END Microsoft Specific
Streaming SIMD Extensions Supported by 3DNow!
Floating-Point Intrinsics Using Streaming SIMD Extensions
Miscellaneous Intrinsics Using Streaming SIMD Extensions
Memory and Initialization Using Streaming SIMD Extensions
Integer Intrinsics Using Streaming SIMD Extensions
Cache Support Using Streaming SIMD Extensions
In addition, the following macro functions are described:
Macro Function for Shuffle Using Streaming SIMD Extensions
Macro Functions to Read and Write the Control Registers
Macro Function for Matrix Transposition
The header file xmmintrin.h contains the declarations for the SSE intrinsics. The file fvec.h contains operator overloads for some of the SSE intrinsics, which are available for use in C++ programs.
SSE intrinsics use the __m128, __m128i, and __m128d data types, which are not supported on Itanium Processor Family (IPF) processors. Any SSE intrinsics that use the __m64 data type are not supported on x64 processors.
END Microsoft Specific
AMD 3DNow! Technology Overview and Intrinsics
Microsoft SpecificThe AMD 3DNow! technology is a group of instructions that opens the traditional processing bottlenecks for multimedia and floating-point-intensive applications. The 3DNow! technology enables faster frame rates on high-resolution scenes, much better physical modeling of real-world environments, sharper and more detailed 3D imaging, smoother video playback, and near-theater–quality audio.
The 3DNow! technology is compatible with today's existing x86 software and requires no operating system support, allowing 3DNow! applications to work with all existing operating systems. This technology is implemented by processors from AMD beginning with AMD-K6-2, AMD-K6-III, and AMD Athlon processors.
Beginning with the AMD Athlon processor, 3DNow! technology has been enhanced to add five new 3DNow! digital signal processing (DSP) instructions and 19 MMX Extensions, including streaming functionality.
This overview of AMD 3DNow! technology contains the following sections:
Key Functionality
Feature Detection
Register Set
Data Types
3DNow! Instruction Formats
Intrinsics Overview
Task Switching
Exceptions
Prefixes
3DNow! Intrinsics
END Microsoft Specific
The 3DNow! technology is compatible with today's existing x86 software and requires no operating system support, allowing 3DNow! applications to work with all existing operating systems. This technology is implemented by processors from AMD beginning with AMD-K6-2, AMD-K6-III, and AMD Athlon processors.
Beginning with the AMD Athlon processor, 3DNow! technology has been enhanced to add five new 3DNow! digital signal processing (DSP) instructions and 19 MMX Extensions, including streaming functionality.
This overview of AMD 3DNow! technology contains the following sections:
Key Functionality
Feature Detection
Register Set
Data Types
3DNow! Instruction Formats
Intrinsics Overview
Task Switching
Exceptions
Prefixes
3DNow! Intrinsics
END Microsoft Specific
Intel Overview of New Instructions and Extensions
Microsoft Specific
The Pentium III Processor and other processors such as the Pentium processor with MMX technology and Pentium II processor have instructions to enable development of optimized multimedia applications. The instructions are implemented through extensions to previously implemented instructions. This technology uses the single-instruction, multiple-data (SIMD) technique. By processing data elements in parallel, applications with media-rich bitstreams can significantly improve performance by using SIMD instructions.
You can access the Intel performance libraries at http://developer.intel.com/.
The most direct way to use these instructions is to inline the assembly language instructions into your source code. However, this can be time consuming and tedious. Instead, Intel provides easy implementation by using API extension sets, referred to as intrinsics.
Intrinsics Availability on Intel Processors
Processors MMX technology intrinsics Streaming SIMD Extensions (SSE) Streaming SIMD Extensions 2 (SSE2) instructions Processors that support SSE2YesYesYesPentium III YesYesNot availablePentium II YesNot availableNot availablePentium with MMX technologyYesNot availableNot availablePentium Pro Not availableNot availableNot availablePentium Not availableNot availableNot available
The following topics are covered:
Benefits of Using Intrinsics
Intrinsic Conventions
Intrinsic Categories and Supporting Extensions
END Microsoft Specific
The Pentium III Processor and other processors such as the Pentium processor with MMX technology and Pentium II processor have instructions to enable development of optimized multimedia applications. The instructions are implemented through extensions to previously implemented instructions. This technology uses the single-instruction, multiple-data (SIMD) technique. By processing data elements in parallel, applications with media-rich bitstreams can significantly improve performance by using SIMD instructions.
You can access the Intel performance libraries at http://developer.intel.com/.
The most direct way to use these instructions is to inline the assembly language instructions into your source code. However, this can be time consuming and tedious. Instead, Intel provides easy implementation by using API extension sets, referred to as intrinsics.
Intrinsics Availability on Intel Processors
Processors MMX technology intrinsics Streaming SIMD Extensions (SSE) Streaming SIMD Extensions 2 (SSE2) instructions Processors that support SSE2YesYesYesPentium III YesYesNot availablePentium II YesNot availableNot availablePentium with MMX technologyYesNot availableNot availablePentium Pro Not availableNot availableNot availablePentium Not availableNot availableNot available
The following topics are covered:
Benefits of Using Intrinsics
Intrinsic Conventions
Intrinsic Categories and Supporting Extensions
END Microsoft Specific
Compiler Support for the MMX, SSE, and SSE2 Intrinsics
Microsoft SpecificTo support the use of MMX, SSE, and SSE2 intrinsics, the compiler includes the following features:
Data alignment
Inline assembly
Data AlignmentPreviously, alignment issues in programs were addressed either by the compiler or directly in hardware. Also, any alignment changes needed for a program to run correctly were automatically enabled. However, with the advent of intrinsic support, the user must take a more active role to guarantee that alignment issues are appropriately addressed.
Many of the new intrinsics have data alignment requirements. If these intrinsics are used and data is not appropriately aligned, the program will throw an exception that must be handled by the program; otherwise, the program will fault.
The new intrinsics require aligned data to allow better performance. With the size of new registers implemented to support the new, enhanced instruction sets, new alignment requirements were defined to make the best use of recent cache architectures. Specific alignment requirements for each intrinsic can be found in the documentation for the intrinsic.
There are different tools to specify appropriate rules for the alignment of data. For alignment of user declared variables, for example, static or automatic data, refer to the align section documentation. For data dynamically allocated from the heap, refer to the data alignment functions.
Note The __m64, __m128, __m128i and __m128d new data types already have an alignment value.
align
__alignof
Inline AssemblyThe compiler supports use of intrinsic assembly instructions in inline assembly (__asm) blocks. The compiler also accepts the new syntax MMWORD PTR and XMMWORD PTR to refer to 64- and 128-bit data.
END Microsoft SpecificFor information on how to detect the capabilities of a CPU, see CPUID
Data alignment
Inline assembly
Data AlignmentPreviously, alignment issues in programs were addressed either by the compiler or directly in hardware. Also, any alignment changes needed for a program to run correctly were automatically enabled. However, with the advent of intrinsic support, the user must take a more active role to guarantee that alignment issues are appropriately addressed.
Many of the new intrinsics have data alignment requirements. If these intrinsics are used and data is not appropriately aligned, the program will throw an exception that must be handled by the program; otherwise, the program will fault.
The new intrinsics require aligned data to allow better performance. With the size of new registers implemented to support the new, enhanced instruction sets, new alignment requirements were defined to make the best use of recent cache architectures. Specific alignment requirements for each intrinsic can be found in the documentation for the intrinsic.
There are different tools to specify appropriate rules for the alignment of data. For alignment of user declared variables, for example, static or automatic data, refer to the align section documentation. For data dynamically allocated from the heap, refer to the data alignment functions.
Note The __m64, __m128, __m128i and __m128d new data types already have an alignment value.
align
__alignof
Inline AssemblyThe compiler supports use of intrinsic assembly instructions in inline assembly (__asm) blocks. The compiler also accepts the new syntax MMWORD PTR and XMMWORD PTR to refer to 64- and 128-bit data.
END Microsoft SpecificFor information on how to detect the capabilities of a CPU, see CPUID
MMX, SSE, and SSE2 Intrinsics
This section discusses intrinsic support for the enhanced instruction sets supported by Intel and Advanced Micro Devices (AMD) processors.
Microsoft SpecificCompiler Support for the MMX, SSE, and SSE2 Intrinsics
Intel Technology Overview of New Instructions and Extensions
AMD 3DNow! Technology Overview and Intrinsics
MMX Technology
Streaming SIMD Extensions (SSE)
Streaming SIMD Extensions 2 (SSE2) Instructions
An intrinsic is a function known by the compiler that directly maps to a sequence of one or more assembly language instructions. Intrinsic functions are inherently more efficient than called functions because no calling linkage is required.
Intrinsics make the use of processor-specific enhancements easier because they provide a C/C++ language interface to assembly instructions. In doing so, the compiler manages things that the user would normally have to be concerned with, such as register names, register allocations, and memory locations of data.
For information on how to detect the capabilities of a CPU, see CPUID Sample: Determines CPU Capabilities.
All the MMX, SSE and SSE2 intrinsics are only available as intrinsics, thus, they are not affected by the setting of /Oi, and #pragma function may not be used on them.
END Microsoft Specific
Microsoft SpecificCompiler Support for the MMX, SSE, and SSE2 Intrinsics
Intel Technology Overview of New Instructions and Extensions
AMD 3DNow! Technology Overview and Intrinsics
MMX Technology
Streaming SIMD Extensions (SSE)
Streaming SIMD Extensions 2 (SSE2) Instructions
An intrinsic is a function known by the compiler that directly maps to a sequence of one or more assembly language instructions. Intrinsic functions are inherently more efficient than called functions because no calling linkage is required.
Intrinsics make the use of processor-specific enhancements easier because they provide a C/C++ language interface to assembly instructions. In doing so, the compiler manages things that the user would normally have to be concerned with, such as register names, register allocations, and memory locations of data.
For information on how to detect the capabilities of a CPU, see CPUID Sample: Determines CPU Capabilities.
All the MMX, SSE and SSE2 intrinsics are only available as intrinsics, thus, they are not affected by the setting of /Oi, and #pragma function may not be used on them.
END Microsoft Specific
Exception Handling in Visual C++
Robust code anticipates and handles exceptions. Exceptions occur when a program executes abnormally because of conditions outside the program's control. Certain operations, including object creation and file input/output, are subject to failures that go beyond errors. Out-of-memory conditions, for example, can occur even when your program is running correctly.
Abnormal situations should be handled by throwing and catching exceptions. Such situations are not the same as normal error conditions, such as a function executing correctly, but returning a result code indicating an error. A normal error condition, for example, would be a file status function indicating that a file does not exist. For normal error conditions, the program should examine the error code and respond appropriately.
Abnormal situations are also not the same as erroneous execution, in which, for example, the caller makes a mistake in passing arguments to a function or calls it in an inappropriate context. For erroneous execution, test your inputs and other assumptions with an assertion (see Using Assertions).
Visual C++ supports three kinds of exception handling:
C++ exception handling
Although structured exception handling works with C and C++ source files, it is not specifically designed for C++. For C++ programs, you should use C++ exception handling.
Structured exception handling
Windows supplies its own exception mechanism, called SEH. It is not recommended for C++ or MFC programming. Use SEH only in non-MFC C programs.
MFC exceptions
Since version 3.0, MFC has used C++ exceptions but still supports its older exception handling macros, which are similar to C++ exceptions in form. The older MFC exception handling macros have been supported since version 1.0. Although these macros are not recommended for new programming, they are still supported for backward compatibility. In programs that already use the macros, you can freely use C++ exceptions as well. During preprocessing, the macros evaluate to the exception handling keywords defined in the Visual C++ implementation of the C++ language as of Visual C++ version 2.0. You can leave existing exception macros in place while you begin to use C++ exceptions.
Do not mix the error handling mechanisms; for example, do not use C++ exceptions with SEH. For advice about mixing MFC macros and C++ exceptions, see Exceptions: Using MFC Macros and C++ Exceptions.
For information on handling exceptions in CLR applications, see Exception Handling under /clr.
For information about exception handling on x64 processors, see Exception Handling (x64).
Abnormal situations should be handled by throwing and catching exceptions. Such situations are not the same as normal error conditions, such as a function executing correctly, but returning a result code indicating an error. A normal error condition, for example, would be a file status function indicating that a file does not exist. For normal error conditions, the program should examine the error code and respond appropriately.
Abnormal situations are also not the same as erroneous execution, in which, for example, the caller makes a mistake in passing arguments to a function or calls it in an inappropriate context. For erroneous execution, test your inputs and other assumptions with an assertion (see Using Assertions).
Visual C++ supports three kinds of exception handling:
C++ exception handling
Although structured exception handling works with C and C++ source files, it is not specifically designed for C++. For C++ programs, you should use C++ exception handling.
Structured exception handling
Windows supplies its own exception mechanism, called SEH. It is not recommended for C++ or MFC programming. Use SEH only in non-MFC C programs.
MFC exceptions
Since version 3.0, MFC has used C++ exceptions but still supports its older exception handling macros, which are similar to C++ exceptions in form. The older MFC exception handling macros have been supported since version 1.0. Although these macros are not recommended for new programming, they are still supported for backward compatibility. In programs that already use the macros, you can freely use C++ exceptions as well. During preprocessing, the macros evaluate to the exception handling keywords defined in the Visual C++ implementation of the C++ language as of Visual C++ version 2.0. You can leave existing exception macros in place while you begin to use C++ exceptions.
Do not mix the error handling mechanisms; for example, do not use C++ exceptions with SEH. For advice about mixing MFC macros and C++ exceptions, see Exceptions: Using MFC Macros and C++ Exceptions.
For information on handling exceptions in CLR applications, see Exception Handling under /clr.
For information about exception handling on x64 processors, see Exception Handling (x64).
Calling Conventions
This section describes the process that one function (caller) makes call into another function (callee).
For prototyped functions, all arguments are converted to the expected callee types before passing.
Parameter Passing
Varargs
Unprototyped Functions
Return Values
Caller/Callee Saved Registers
Function Pointers
Legacy Floating-Point Support
FpCsr
MXCSR
setjmp/longjump
The Visual C/C++ compiler provides several different conventions for calling internal and external functions. Understanding these different approaches can help you debug your program and link your code with assembly-language routines.
The topics on this subject explain the differences between the calling conventions, how arguments are passed, and how values are returned by functions. They also discuss naked function calls, an advanced feature that enables you to write your own prolog and epilog code.
For prototyped functions, all arguments are converted to the expected callee types before passing.
Parameter Passing
Varargs
Unprototyped Functions
Return Values
Caller/Callee Saved Registers
Function Pointers
Legacy Floating-Point Support
FpCsr
MXCSR
setjmp/longjump
The Visual C/C++ compiler provides several different conventions for calling internal and external functions. Understanding these different approaches can help you debug your program and link your code with assembly-language routines.
The topics on this subject explain the differences between the calling conventions, how arguments are passed, and how values are returned by functions. They also discuss naked function calls, an advanced feature that enables you to write your own prolog and epilog code.
Create Directory

#pragma once
namespace My57 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
///
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnCreateDirectory;
private: System::Windows::Forms::TextBox^ txtDirectoryName;
protected:
private: System::Windows::Forms::Label^ lbl;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnCreateDirectory = (gcnew System::Windows::Forms::Button());
this->txtDirectoryName = (gcnew System::Windows::Forms::TextBox());
this->lbl = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// BtnCreateDirectory
//
this->BtnCreateDirectory->BackColor = System::Drawing::Color::FromArgb(static_cast
static_cast
this->BtnCreateDirectory->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast
this->BtnCreateDirectory->ForeColor = System::Drawing::Color::White;
this->BtnCreateDirectory->Location = System::Drawing::Point(11, 88);
this->BtnCreateDirectory->Name = L"BtnCreateDirectory";
this->BtnCreateDirectory->Size = System::Drawing::Size(266, 94);
this->BtnCreateDirectory->TabIndex = 0;
this->BtnCreateDirectory->Text = L"Create Directory";
this->BtnCreateDirectory->UseVisualStyleBackColor = false;
this->BtnCreateDirectory->Click += gcnew System::EventHandler(this, &Form1::BtnCreateDirectory_Click);
//
// txtDirectoryName
//
this->txtDirectoryName->BackColor = System::Drawing::Color::FromArgb(static_cast
static_cast
this->txtDirectoryName->ForeColor = System::Drawing::Color::Blue;
this->txtDirectoryName->Location = System::Drawing::Point(21, 48);
this->txtDirectoryName->Name = L"txtDirectoryName";
this->txtDirectoryName->Size = System::Drawing::Size(256, 20);
this->txtDirectoryName->TabIndex = 1;
//
// lbl
//
this->lbl->AutoSize = true;
this->lbl->ForeColor = System::Drawing::Color::Yellow;
this->lbl->Location = System::Drawing::Point(17, 16);
this->lbl->Name = L"lbl";
this->lbl->Size = System::Drawing::Size(89, 13);
this->lbl->TabIndex = 2;
this->lbl->Text = L"Directory Name : ";
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::Color::FromArgb(static_cast
static_cast
this->ClientSize = System::Drawing::Size(292, 197);
this->Controls->Add(this->lbl);
this->Controls->Add(this->txtDirectoryName);
this->Controls->Add(this->BtnCreateDirectory);
this->Name = L"Form1";
this->Text = L"Form1";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//Create Directory
private: System::Void BtnCreateDirectory_Click(System::Object^ sender, System::EventArgs^ e) {
if(txtDirectoryName->Text!="")
{
Directory::CreateDirectory("C:\\"+txtDirectoryName->Text);
MessageBox::Show("Create Directory Completed");
}
}
};
}
Scroll Form

#pragma once
namespace My56 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnScrollForm;
private: System::Windows::Forms::PictureBox^ PctImage;
protected:
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid));
this->BtnScrollForm = (gcnew System::Windows::Forms::Button());
this->PctImage = (gcnew System::Windows::Forms::PictureBox());
(cli::safe_cast
this->SuspendLayout();
//
// BtnScrollForm
//
this->BtnScrollForm->Location = System::Drawing::Point(12, 12);
this->BtnScrollForm->Name = L"BtnScrollForm";
this->BtnScrollForm->Size = System::Drawing::Size(332, 45);
this->BtnScrollForm->TabIndex = 0;
this->BtnScrollForm->Text = L"Scroll Form";
this->BtnScrollForm->UseVisualStyleBackColor = true;
this->BtnScrollForm->Click += gcnew System::EventHandler(this, &Form1::BtnScrollForm_Click);
//
// PctImage
//
this->PctImage->Image = (cli::safe_cast
this->PctImage->Location = System::Drawing::Point(13, 73);
this->PctImage->Name = L"PctImage";
this->PctImage->Size = System::Drawing::Size(715, 344);
this->PctImage->TabIndex = 1;
this->PctImage->TabStop = false;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(357, 125);
this->Controls->Add(this->PctImage);
this->Controls->Add(this->BtnScrollForm);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
(cli::safe_cast
this->ResumeLayout(false);
}
#pragma endregion
//Scroll Form
private: System::Void BtnScrollForm_Click(System::Object^ sender, System::EventArgs^ e) {
this->AutoScroll=true;
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Scroll Form";
this->BackColor=Color::AliceBlue;
this->MaximizeBox=false;
BtnScrollForm->BackColor=Color::Black;
BtnScrollForm->ForeColor=Color::White;
}
};
}
Region Form

#pragma once
namespace My55 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->DoubleClick += gcnew System::EventHandler(this, &Form1::Form1_DoubleClick);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Region Form
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->FormBorderStyle=Windows::Forms::FormBorderStyle::None;
this->BackgroundImageLayout=Windows::Forms::ImageLayout::Stretch;
this->BackgroundImage=Image::FromFile("C:\\Character.BMP");
this->TransparencyKey=Color::Black;
}
private: System::Void Form1_DoubleClick(System::Object^ sender, System::EventArgs^ e) {
this->Close();
}
};
}
Return Value in Function

#pragma once
namespace My54 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnReturn;
private: System::Windows::Forms::Label^ lblReturnValue;
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnReturn = (gcnew System::Windows::Forms::Button());
this->lblReturnValue = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// BtnReturn
//
this->BtnReturn->BackColor = System::Drawing::Color::FromArgb(static_cast
static_cast
this->BtnReturn->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast
this->BtnReturn->ForeColor = System::Drawing::Color::White;
this->BtnReturn->Location = System::Drawing::Point(12, 66);
this->BtnReturn->Name = L"BtnReturn";
this->BtnReturn->Size = System::Drawing::Size(268, 63);
this->BtnReturn->TabIndex = 0;
this->BtnReturn->Text = L"Return Value";
this->BtnReturn->UseVisualStyleBackColor = false;
this->BtnReturn->Click += gcnew System::EventHandler(this, &Form1::BtnReturn_Click);
//
// lblReturnValue
//
this->lblReturnValue->AutoSize = true;
this->lblReturnValue->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 11.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast
this->lblReturnValue->ForeColor = System::Drawing::Color::Yellow;
this->lblReturnValue->Location = System::Drawing::Point(12, 25);
this->lblReturnValue->Name = L"lblReturnValue";
this->lblReturnValue->Size = System::Drawing::Size(114, 18);
this->lblReturnValue->TabIndex = 2;
this->lblReturnValue->Text = L"Return Value :";
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::SystemColors::ControlDark;
this->ClientSize = System::Drawing::Size(292, 142);
this->Controls->Add(this->lblReturnValue);
this->Controls->Add(this->BtnReturn);
this->Name = L"Form1";
this->Text = L"Return Value In Function";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//Return Value in Function
int Ch_X;
int MoveX(int Step)
{
Ch_X+=Step;
return Ch_X;
}
private: System::Void BtnReturn_Click(System::Object^ sender, System::EventArgs^ e) {
lblReturnValue->Text="Return Value : "+MoveX(2);
}
};
}
Property Count In ListBox

#pragma once
namespace My53 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ Btn;
private: System::Windows::Forms::ComboBox^ Cmb;
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->Btn = (gcnew System::Windows::Forms::Button());
this->Cmb = (gcnew System::Windows::Forms::ComboBox());
this->SuspendLayout();
//
// Btn
//
this->Btn->Location = System::Drawing::Point(12, 73);
this->Btn->Name = L"Btn";
this->Btn->Size = System::Drawing::Size(268, 50);
this->Btn->TabIndex = 0;
this->Btn->Text = L"Show Count Items ";
this->Btn->UseVisualStyleBackColor = true;
this->Btn->Click += gcnew System::EventHandler(this, &Form1::Btn_Click);
//
// Cmb
//
this->Cmb->FormattingEnabled = true;
this->Cmb->Location = System::Drawing::Point(12, 28);
this->Cmb->Name = L"Cmb";
this->Cmb->Size = System::Drawing::Size(268, 21);
this->Cmb->TabIndex = 1;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 134);
this->Controls->Add(this->Cmb);
this->Controls->Add(this->Btn);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregio
//Property Count In ListBox
private: System::Void Btn_Click(System::Object^ sender, System::EventArgs^ e) {
int i;
String^str;
str="www.cplusplussourcecode.blogspot.com";
for(i=0;i<=str->Length;i++)
{
Cmb->Items->Add(str);
}
this->Text=Cmb->Items->Count.ToString();
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->BackColor=Color::Blue;
this->Text="Property Count In ListBox";
this->MaximizeBox=false;
Cmb->BackColor=Color::Red;
Cmb->ForeColor=Color::White;
Btn->BackColor=Color::Black;
Btn->ForeColor=Color::White;
}
};
}
Using for Add Items in ListBox

#pragma once
namespace My52 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnAddItems;
protected:
private: System::Windows::Forms::ListBox^ lst;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnAddItems = (gcnew System::Windows::Forms::Button());
this->lst = (gcnew System::Windows::Forms::ListBox());
this->SuspendLayout();
//
// BtnAddItems
//
this->BtnAddItems->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast
this->BtnAddItems->Location = System::Drawing::Point(12, 149);
this->BtnAddItems->Name = L"BtnAddItems";
this->BtnAddItems->Size = System::Drawing::Size(377, 42);
this->BtnAddItems->TabIndex = 0;
this->BtnAddItems->Text = L"Add Items";
this->BtnAddItems->UseVisualStyleBackColor = true;
this->BtnAddItems->Click += gcnew System::EventHandler(this, &Form1::BtnAddItems_Click);
//
// lst
//
this->lst->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 15.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast
this->lst->FormattingEnabled = true;
this->lst->ItemHeight = 25;
this->lst->Location = System::Drawing::Point(14, 19);
this->lst->Name = L"lst";
this->lst->Size = System::Drawing::Size(375, 104);
this->lst->TabIndex = 1;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(401, 203);
this->Controls->Add(this->lst);
this->Controls->Add(this->BtnAddItems);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Using for Add Items in ListBox
private: System::Void BtnAddItems_Click(System::Object^ sender, System::EventArgs^ e) {
int i;
for(i=0;i<=50;i++) { lst->Items->Add("Index : "+i);
}
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->BackColor=Color::Red;
this->Text="Using for Add Items in ListBox";
this->MaximizeBox=false;
lst->BackColor=Color::Yellow;
lst->ForeColor=Color::Red;
BtnAddItems->BackColor=Color::Black;
BtnAddItems->ForeColor=Color::White;
}
};
}
Select Items in ComboBox

#pragma once
namespace My51 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::ComboBox^ Cmb;
protected:
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->Cmb = (gcnew System::Windows::Forms::ComboBox());
this->SuspendLayout();
//
// Cmb
//
this->Cmb->FormattingEnabled = true;
this->Cmb->Location = System::Drawing::Point(12, 12);
this->Cmb->Name = L"Cmb";
this->Cmb->Size = System::Drawing::Size(268, 21);
this->Cmb->TabIndex = 1;
this->Cmb->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::Cmb_SelectedIndexChanged);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 47);
this->Controls->Add(this->Cmb);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Select Items in ComboBox
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
Cmb->Items->Add("Items 1");
Cmb->Items->Add("Items 2");
Cmb->Items->Add("Items 3");
Cmb->Items->Add("Items 4");
this->Text="Select Items in ComboBox";
this->MaximizeBox=false;
this->BackColor=Color::Plum;
Cmb->BackColor=Color::Yellow;
Cmb->ForeColor=Color::Blue;
}
private: System::Void Cmb_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
this->Text=Cmb->Text;
}
};
}
Show FolderBrowserDialog

#pragma once
namespace My50 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::FolderBrowserDialog^ FolderBrowserDialog;
private: System::Windows::Forms::Button^ BtnShowFolderBrowserDialog;
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->FolderBrowserDialog = (gcnew System::Windows::Forms::FolderBrowserDialog());
this->BtnShowFolderBrowserDialog = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// BtnShowFolderBrowserDialog
//
this->BtnShowFolderBrowserDialog->Location = System::Drawing::Point(12, 14);
this->BtnShowFolderBrowserDialog->Name = L"BtnShowFolderBrowserDialog";
this->BtnShowFolderBrowserDialog->Size = System::Drawing::Size(240, 42);
this->BtnShowFolderBrowserDialog->TabIndex = 0;
this->BtnShowFolderBrowserDialog->Text = L"Show FolderBrowserDialog";
this->BtnShowFolderBrowserDialog->UseVisualStyleBackColor = true;
this->BtnShowFolderBrowserDialog->Click += gcnew System::EventHandler(this, &Form1::BtnShowFolderBrowserDialog_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(263, 68);
this->Controls->Add(this->BtnShowFolderBrowserDialog);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Show FolderBrowserDialog
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Show FolderBrowesDialog";
this->BackColor=Color::Pink;
this->MaximizeBox=false;
BtnShowFolderBrowserDialog->BackColor=Color::Black;
BtnShowFolderBrowserDialog->ForeColor=Color::White;
}
private: System::Void BtnShowFolderBrowserDialog_Click(System::Object^ sender, System::EventArgs^ e) {
FolderBrowserDialog->RootFolder=Environment::SpecialFolder::MyDocuments;
FolderBrowserDialog->ShowDialog();
}
};
}
GetCreateTime File

#pragma once
namespace My49 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
///
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ lblCreateTime;
protected:
private: System::Windows::Forms::Label^ lblPathFile;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->lblCreateTime = (gcnew System::Windows::Forms::Label());
this->lblPathFile = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// lblCreateTime
//
this->lblCreateTime->AutoSize = true;
this->lblCreateTime->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast
this->lblCreateTime->ForeColor = System::Drawing::Color::White;
this->lblCreateTime->Location = System::Drawing::Point(12, 41);
this->lblCreateTime->Name = L"lblCreateTime";
this->lblCreateTime->Size = System::Drawing::Size(97, 16);
this->lblCreateTime->TabIndex = 0;
this->lblCreateTime->Text = L"CreateTime :";
//
// lblPathFile
//
this->lblPathFile->AutoSize = true;
this->lblPathFile->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast
this->lblPathFile->ForeColor = System::Drawing::Color::White;
this->lblPathFile->Location = System::Drawing::Point(12, 9);
this->lblPathFile->Name = L"lblPathFile";
this->lblPathFile->Size = System::Drawing::Size(77, 16);
this->lblPathFile->TabIndex = 1;
this->lblPathFile->Text = L"Path File :";
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(553, 64);
this->Controls->Add(this->lblPathFile);
this->Controls->Add(this->lblCreateTime);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//GetCreateTime File
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
lblCreateTime->Text="Create Time : "+File::GetCreationTime("C:\\Flower.BMP").ToString();
lblPathFile->Text="Path File : C:\\Flower.BMP";
this->Text="GetCreateTime File";
this->BackColor=Color::RosyBrown;
this->MaximizeBox=false;
}
};
}
Play Sound

#pragma once
namespace My48 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: AxWMPLib::AxWindowsMediaPlayer^ w;
protected:
private: System::Windows::Forms::Button^ BtnPlay;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid));
this->w = (gcnew AxWMPLib::AxWindowsMediaPlayer());
this->BtnPlay = (gcnew System::Windows::Forms::Button());
(cli::safe_cast
this->SuspendLayout();
//
// w
//
this->w->Enabled = true;
this->w->Location = System::Drawing::Point(11, 13);
this->w->Name = L"w";
this->w->OcxState = (cli::safe_cast
this->w->Size = System::Drawing::Size(269, 184);
this->w->TabIndex = 0;
//
// BtnPlay
//
this->BtnPlay->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 14.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast
this->BtnPlay->Location = System::Drawing::Point(12, 211);
this->BtnPlay->Name = L"BtnPlay";
this->BtnPlay->Size = System::Drawing::Size(267, 45);
this->BtnPlay->TabIndex = 1;
this->BtnPlay->Text = L"Play";
this->BtnPlay->UseVisualStyleBackColor = true;
this->BtnPlay->Click += gcnew System::EventHandler(this, &Form1::BtnPlay_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Controls->Add(this->BtnPlay);
this->Controls->Add(this->w);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
(cli::safe_cast
this->ResumeLayout(false);
}
#pragma endregion
//Play Sound
private: System::Void BtnPlay_Click(System::Object^ sender, System::EventArgs^ e) {
w->URL="D:\\Song\\01 Track 1.mp3";
w->Ctlcontrols->play();
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Play Sound";
this->BackColor=Color::Yellow;
this->MaximizeBox=false;
BtnPlay->BackColor=Color::Black;
BtnPlay->ForeColor=Color::White;
}
};
}
Draw Image on RichTextBox

#pragma once
namespace My47 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::RichTextBox^ Rtf;
private: System::Windows::Forms::Button^ BtnDrawImage;
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->Rtf = (gcnew System::Windows::Forms::RichTextBox());
this->BtnDrawImage = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// Rtf
//
this->Rtf->Location = System::Drawing::Point(12, 11);
this->Rtf->Name = L"Rtf";
this->Rtf->Size = System::Drawing::Size(268, 190);
this->Rtf->TabIndex = 0;
this->Rtf->Text = L"";
//
// BtnDrawImage
//
this->BtnDrawImage->Location = System::Drawing::Point(12, 216);
this->BtnDrawImage->Name = L"BtnDrawImage";
this->BtnDrawImage->Size = System::Drawing::Size(267, 35);
this->BtnDrawImage->TabIndex = 1;
this->BtnDrawImage->Text = L"Draw Image";
this->BtnDrawImage->UseVisualStyleBackColor = true;
this->BtnDrawImage->Click += gcnew System::EventHandler(this, &Form1::BtnDrawImage_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Controls->Add(this->BtnDrawImage);
this->Controls->Add(this->Rtf);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Draw Image on RichTextBox
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
Rtf->BackColor=Color::Red;
this->Text="DrawImage on RichTextBox";
this->FormBorderStyle=Windows::Forms::FormBorderStyle::FixedToolWindow;
this->BackColor=Color::Gray;
}
private: System::Void BtnDrawImage_Click(System::Object^ sender, System::EventArgs^ e) {
Graphics^g;
Bitmap^b;
b=gcnew Bitmap("C:\\Flower.Bmp");
g=Rtf->CreateGraphics();
g->DrawImage(b,Rectangle(10,10,200,200));
}
};
}
Copy And Paste in RichTextBox

#pragma once
namespace My46 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::RichTextBox^ Rtf;
protected:
private: System::Windows::Forms::Button^ BtnCopy;
private: System::Windows::Forms::Button^ BtnPaste;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->Rtf = (gcnew System::Windows::Forms::RichTextBox());
this->BtnCopy = (gcnew System::Windows::Forms::Button());
this->BtnPaste = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// Rtf
//
this->Rtf->Location = System::Drawing::Point(10, 12);
this->Rtf->Name = L"Rtf";
this->Rtf->Size = System::Drawing::Size(272, 204);
this->Rtf->TabIndex = 0;
this->Rtf->Text = L"";
//
// BtnCopy
//
this->BtnCopy->Location = System::Drawing::Point(12, 222);
this->BtnCopy->Name = L"BtnCopy";
this->BtnCopy->Size = System::Drawing::Size(121, 32);
this->BtnCopy->TabIndex = 1;
this->BtnCopy->Text = L"Copy";
this->BtnCopy->UseVisualStyleBackColor = true;
this->BtnCopy->Click += gcnew System::EventHandler(this, &Form1::BtnCopy_Click);
//
// BtnPaste
//
this->BtnPaste->Location = System::Drawing::Point(150, 222);
this->BtnPaste->Name = L"BtnPaste";
this->BtnPaste->Size = System::Drawing::Size(130, 32);
this->BtnPaste->TabIndex = 2;
this->BtnPaste->Text = L"Paste";
this->BtnPaste->UseVisualStyleBackColor = true;
this->BtnPaste->Click += gcnew System::EventHandler(this, &Form1::BtnPaste_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Controls->Add(this->BtnPaste);
this->Controls->Add(this->BtnCopy);
this->Controls->Add(this->Rtf);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Copy And Paste in RichTextBox
private: System::Void BtnCopy_Click(System::Object^ sender, System::EventArgs^ e) {
Rtf->Copy();
}
private: System::Void BtnPaste_Click(System::Object^ sender, System::EventArgs^ e) {
Rtf->Paste();
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Copy And Paste in RichTextBox";
this->BackColor=Color::Yellow;
this->MaximizeBox=false;
}
};
}
Show TextLength

#pragma once
namespace My45 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::RichTextBox^ Rtf;
private: System::Windows::Forms::Button^ BtnTextLength;
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->Rtf = (gcnew System::Windows::Forms::RichTextBox());
this->BtnTextLength = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// Rtf
//
this->Rtf->Location = System::Drawing::Point(9, 14);
this->Rtf->Name = L"Rtf";
this->Rtf->Size = System::Drawing::Size(271, 194);
this->Rtf->TabIndex = 0;
this->Rtf->Text = L"";
//
// BtnTextLength
//
this->BtnTextLength->Location = System::Drawing::Point(12, 223);
this->BtnTextLength->Name = L"BtnTextLength";
this->BtnTextLength->Size = System::Drawing::Size(267, 31);
this->BtnTextLength->TabIndex = 1;
this->BtnTextLength->Text = L"Show TextLength";
this->BtnTextLength->UseVisualStyleBackColor = true;
this->BtnTextLength->Click += gcnew System::EventHandler(this, &Form1::BtnSave_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Controls->Add(this->BtnTextLength);
this->Controls->Add(this->Rtf);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Show TextLength
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Show TextLength";
this->BackColor=Color::Black;
this->MaximizeBox=false;
Rtf->BackColor=Color::Yellow;
Rtf->ForeColor=Color::Blue;
}
private: System::Void BtnSave_Click(System::Object^ sender, System::EventArgs^ e) {
this->Text=Rtf->TextLength.ToString();
}
};
}
MixColor

#pragma once
namespace My44 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::NumericUpDown^ nRed;
protected:
private: System::Windows::Forms::Label^ lblRed;
private: System::Windows::Forms::NumericUpDown^ nGreen;
private: System::Windows::Forms::NumericUpDown^ nBlue;
private: System::Windows::Forms::Label^ lblGreen;
private: System::Windows::Forms::Label^ lblBlue;
private: System::Windows::Forms::PictureBox^ pctResult;
private: System::Windows::Forms::Button^ BtnShowResult;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->nRed = (gcnew System::Windows::Forms::NumericUpDown());
this->lblRed = (gcnew System::Windows::Forms::Label());
this->nGreen = (gcnew System::Windows::Forms::NumericUpDown());
this->nBlue = (gcnew System::Windows::Forms::NumericUpDown());
this->lblGreen = (gcnew System::Windows::Forms::Label());
this->lblBlue = (gcnew System::Windows::Forms::Label());
this->pctResult = (gcnew System::Windows::Forms::PictureBox());
this->BtnShowResult = (gcnew System::Windows::Forms::Button());
(cli::safe_cast
(cli::safe_cast
(cli::safe_cast
(cli::safe_cast
this->SuspendLayout();
//
// nRed
//
this->nRed->Location = System::Drawing::Point(51, 22);
this->nRed->Name = L"nRed";
this->nRed->Size = System::Drawing::Size(43, 20);
this->nRed->TabIndex = 0;
this->nRed->ValueChanged += gcnew System::EventHandler(this, &Form1::nRed_ValueChanged);
//
// lblRed
//
this->lblRed->AutoSize = true;
this->lblRed->Location = System::Drawing::Point(12, 24);
this->lblRed->Name = L"lblRed";
this->lblRed->Size = System::Drawing::Size(33, 13);
this->lblRed->TabIndex = 1;
this->lblRed->Text = L"Red :";
//
// nGreen
//
this->nGreen->Location = System::Drawing::Point(51, 61);
this->nGreen->Name = L"nGreen";
this->nGreen->Size = System::Drawing::Size(43, 20);
this->nGreen->TabIndex = 2;
this->nGreen->ValueChanged += gcnew System::EventHandler(this, &Form1::nGreen_ValueChanged);
//
// nBlue
//
this->nBlue->Location = System::Drawing::Point(51, 97);
this->nBlue->Name = L"nBlue";
this->nBlue->Size = System::Drawing::Size(43, 20);
this->nBlue->TabIndex = 3;
this->nBlue->ValueChanged += gcnew System::EventHandler(this, &Form1::nBlue_ValueChanged);
//
// lblGreen
//
this->lblGreen->AutoSize = true;
this->lblGreen->Location = System::Drawing::Point(12, 63);
this->lblGreen->Name = L"lblGreen";
this->lblGreen->Size = System::Drawing::Size(42, 13);
this->lblGreen->TabIndex = 4;
this->lblGreen->Text = L"Green :";
//
// lblBlue
//
this->lblBlue->AutoSize = true;
this->lblBlue->Location = System::Drawing::Point(12, 99);
this->lblBlue->Name = L"lblBlue";
this->lblBlue->Size = System::Drawing::Size(34, 13);
this->lblBlue->TabIndex = 5;
this->lblBlue->Text = L"Blue :";
//
// pctResult
//
this->pctResult->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;
this->pctResult->Location = System::Drawing::Point(109, 23);
this->pctResult->Name = L"pctResult";
this->pctResult->Size = System::Drawing::Size(170, 102);
this->pctResult->TabIndex = 6;
this->pctResult->TabStop = false;
//
// BtnShowResult
//
this->BtnShowResult->Location = System::Drawing::Point(12, 131);
this->BtnShowResult->Name = L"BtnShowResult";
this->BtnShowResult->Size = System::Drawing::Size(267, 30);
this->BtnShowResult->TabIndex = 7;
this->BtnShowResult->Text = L"Show Result";
this->BtnShowResult->UseVisualStyleBackColor = true;
this->BtnShowResult->Click += gcnew System::EventHandler(this, &Form1::BtnShowResult_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 162);
this->Controls->Add(this->BtnShowResult);
this->Controls->Add(this->pctResult);
this->Controls->Add(this->lblBlue);
this->Controls->Add(this->lblGreen);
this->Controls->Add(this->nBlue);
this->Controls->Add(this->nGreen);
this->Controls->Add(this->lblRed);
this->Controls->Add(this->nRed);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
(cli::safe_cast
(cli::safe_cast
(cli::safe_cast
(cli::safe_cast
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//MixColor
int cRed;
int cGreen;
int cBlue;
void UpdateMixColor()
{
pctResult->BackColor=Color::FromArgb(cRed,cGreen,cBlue);
}
private: System::Void nRed_ValueChanged(System::Object^ sender, System::EventArgs^ e) {
cRed=Convert::ToInt32(nRed->Value);
UpdateMixColor();
}
private: System::Void nGreen_ValueChanged(System::Object^ sender, System::EventArgs^ e) {
cGreen=Convert::ToInt32(nGreen->Value);
UpdateMixColor();
}
private: System::Void nBlue_ValueChanged(System::Object^ sender, System::EventArgs^ e) {
cBlue=Convert::ToInt32(nBlue->Value);
UpdateMixColor();
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
nRed->Maximum=255;
nGreen->Maximum=255;
nBlue->Maximum=255;
this->Text="MixColor";
this->MaximizeBox=false;
}
private: System::Void BtnShowResult_Click(System::Object^ sender, System::EventArgs^ e) {
UpdateMixColor();
}
};
}
Using maskedTextBox

#pragma once
namespace My43 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::MaskedTextBox^ mtxt;
private: System::Windows::Forms::Button^ BtnSee;
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->mtxt = (gcnew System::Windows::Forms::MaskedTextBox());
this->BtnSee = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// mtxt
//
this->mtxt->Location = System::Drawing::Point(12, 12);
this->mtxt->Name = L"mtxt";
this->mtxt->PasswordChar = '*';
this->mtxt->Size = System::Drawing::Size(334, 20);
this->mtxt->TabIndex = 0;
//
// BtnSee
//
this->BtnSee->Location = System::Drawing::Point(16, 41);
this->BtnSee->Name = L"BtnSee";
this->BtnSee->Size = System::Drawing::Size(329, 23);
this->BtnSee->TabIndex = 1;
this->BtnSee->Text = L"See";
this->BtnSee->UseVisualStyleBackColor = true;
this->BtnSee->Click += gcnew System::EventHandler(this, &Form1::BtnSee_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(358, 71);
this->Controls->Add(this->BtnSee);
this->Controls->Add(this->mtxt);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//Using maskedTextBox
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
mtxt->PasswordChar='*';
this->Text="Using maskedTextBox";
this->MaximizeBox=false;
this->BackColor=Color::Gray;
mtxt->BackColor=Color::Yellow;
mtxt->ForeColor=Color::Blue;
}
private: System::Void BtnSee_Click(System::Object^ sender, System::EventArgs^ e) {
this->Text=mtxt->Text;
}
};
}
Eject CD

#pragma once
namespace My42 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: AxWMPLib::AxWindowsMediaPlayer^ w;
protected:
private: System::Windows::Forms::Button^ BtnEjectCD;
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid));
this->w = (gcnew AxWMPLib::AxWindowsMediaPlayer());
this->BtnEjectCD = (gcnew System::Windows::Forms::Button());
(cli::safe_cast
this->SuspendLayout();
//
// w
//
this->w->Enabled = true;
this->w->Location = System::Drawing::Point(12, 12);
this->w->Name = L"w";
this->w->OcxState = (cli::safe_cast
this->w->Size = System::Drawing::Size(10, 10);
this->w->TabIndex = 0;
//
// BtnEjectCD
//
this->BtnEjectCD->Location = System::Drawing::Point(12, 12);
this->BtnEjectCD->Name = L"BtnEjectCD";
this->BtnEjectCD->Size = System::Drawing::Size(264, 53);
this->BtnEjectCD->TabIndex = 1;
this->BtnEjectCD->Text = L"Eject CD";
this->BtnEjectCD->UseVisualStyleBackColor = true;
this->BtnEjectCD->Click += gcnew System::EventHandler(this, &Form1::BtnEjectCD_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(288, 77);
this->Controls->Add(this->BtnEjectCD);
this->Controls->Add(this->w);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
(cli::safe_cast
this->ResumeLayout(false);
}
#pragma endregion
//Eject CD
private: System::Void BtnEjectCD_Click(System::Object^ sender, System::EventArgs^ e) {
w->cdromCollection->getByDriveSpecifier("e")->eject();
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Eject CD";
this->BackColor=Color::Black;
this->MaximizeBox=false;
}
};
}
Open RTF File

#pragma once
namespace My41 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::RichTextBox^ rtf;
protected:
private: System::Windows::Forms::Button^ BtnOpenFile;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->rtf = (gcnew System::Windows::Forms::RichTextBox());
this->BtnOpenFile = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// rtf
//
this->rtf->Location = System::Drawing::Point(12, 12);
this->rtf->Name = L"rtf";
this->rtf->Size = System::Drawing::Size(475, 297);
this->rtf->TabIndex = 0;
this->rtf->Text = L"";
//
// BtnOpenFile
//
this->BtnOpenFile->Location = System::Drawing::Point(12, 315);
this->BtnOpenFile->Name = L"BtnOpenFile";
this->BtnOpenFile->Size = System::Drawing::Size(475, 35);
this->BtnOpenFile->TabIndex = 1;
this->BtnOpenFile->Text = L"Open RTF File";
this->BtnOpenFile->UseVisualStyleBackColor = true;
this->BtnOpenFile->Click += gcnew System::EventHandler(this, &Form1::BtnOpenFile_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(499, 353);
this->Controls->Add(this->BtnOpenFile);
this->Controls->Add(this->rtf);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Open RTF File
private: System::Void BtnOpenFile_Click(System::Object^ sender, System::EventArgs^ e) {
rtf->LoadFile("C:\\RTF.rtf");
rtf->BackColor=Color::Yellow;
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Open RTF File";
this->BackColor=Color::Red;
this->MaximizeBox=false;
}
};
}
Show Animation Form

#pragma once
namespace My40 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Timer^ t;
protected:
private: System::ComponentModel::IContainer^ components;
private:
///
/// Required designer variable.
///
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
this->t = (gcnew System::Windows::Forms::Timer(this->components));
this->SuspendLayout();
//
// t
//
this->t->Interval = 1;
this->t->Tick += gcnew System::EventHandler(this, &Form1::t_Tick);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Show Animation Form
private: System::Void t_Tick(System::Object^ sender, System::EventArgs^ e) {
this->Width=this->Width+5;
this->Height=this->Height+5;
if(this->Width>=300 && this->Height>=300)
{
t->Enabled=false;
}
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Width=10;
this->Height=10;
this->BackColor=Color::Azure;
this->Text="Show Animation Form";
this->MaximizeBox=false;
this->MinimizeBox=false;
t->Enabled=true;
t->Interval=100;
}
};
}
Move Button

#pragma once
namespace My39 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnMoveButton;
protected:
private: System::Windows::Forms::Label^ lblHelp;
private: System::Windows::Forms::Timer^ t;
private: System::ComponentModel::IContainer^ components;
private:
///
/// Required designer variable.
///
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
this->BtnMoveButton = (gcnew System::Windows::Forms::Button());
this->lblHelp = (gcnew System::Windows::Forms::Label());
this->t = (gcnew System::Windows::Forms::Timer(this->components));
this->SuspendLayout();
//
// BtnMoveButton
//
this->BtnMoveButton->Location = System::Drawing::Point(96, 63);
this->BtnMoveButton->Name = L"BtnMoveButton";
this->BtnMoveButton->Size = System::Drawing::Size(98, 16);
this->BtnMoveButton->TabIndex = 0;
this->BtnMoveButton->Text = L"...";
this->BtnMoveButton->UseVisualStyleBackColor = true;
this->BtnMoveButton->Click += gcnew System::EventHandler(this, &Form1::BtnMoveButton_Click);
//
// lblHelp
//
this->lblHelp->AutoSize = true;
this->lblHelp->Location = System::Drawing::Point(93, 25);
this->lblHelp->Name = L"lblHelp";
this->lblHelp->Size = System::Drawing::Size(101, 13);
this->lblHelp->TabIndex = 1;
this->lblHelp->Text = L"Click Button to Start";
//
// t
//
this->t->Interval = 1;
this->t->Tick += gcnew System::EventHandler(this, &Form1::t_Tick);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 95);
this->Controls->Add(this->lblHelp);
this->Controls->Add(this->BtnMoveButton);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//Move Button
private: System::Void BtnMoveButton_Click(System::Object^ sender, System::EventArgs^ e) {
t->Enabled=true;
t->Interval=10;
}
private: System::Void t_Tick(System::Object^ sender, System::EventArgs^ e) {
BtnMoveButton->Left=BtnMoveButton->Left+1;
if(BtnMoveButton->Left>=this->Width)
{
BtnMoveButton->Left=0;
}
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Move Button";
this->BackColor=Color::Aquamarine;
this->MaximizeBox=false;
}
};
}
Using Switch case

#pragma once
namespace My38 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::Form1_MouseDown);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Using Switch case
private: System::Void Form1_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
static int i;
switch(i)
{
case 0:
{
this->BackColor=Color::Red;
}break;
case 1:
{
this->BackColor=Color::Yellow;
}break;
case 2:
{
this->BackColor=Color::Black;
}break;
case 3:
{
this->BackColor=Color::Blue;
}break;
}
i++;
if(i>3)
{
i=0;
}
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Using Switch Case";
this->MaximizeBox=false;
}
};
}
Show Path File

#pragma once
namespace My37 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnShowPathFile;
protected:
private: System::Windows::Forms::Label^ lblPathFile;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnShowPathFile = (gcnew System::Windows::Forms::Button());
this->lblPathFile = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// BtnShowPathFile
//
this->BtnShowPathFile->Location = System::Drawing::Point(12, 99);
this->BtnShowPathFile->Name = L"BtnShowPathFile";
this->BtnShowPathFile->Size = System::Drawing::Size(557, 50);
this->BtnShowPathFile->TabIndex = 0;
this->BtnShowPathFile->Text = L"Show Path File";
this->BtnShowPathFile->UseVisualStyleBackColor = true;
this->BtnShowPathFile->Click += gcnew System::EventHandler(this, &Form1::BtnShowPathFile_Click);
//
// lblPathFile
//
this->lblPathFile->AutoSize = true;
this->lblPathFile->Location = System::Drawing::Point(24, 41);
this->lblPathFile->Name = L"lblPathFile";
this->lblPathFile->Size = System::Drawing::Size(35, 13);
this->lblPathFile->TabIndex = 1;
this->lblPathFile->Text = L"label1";
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(581, 161);
this->Controls->Add(this->lblPathFile);
this->Controls->Add(this->BtnShowPathFile);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//Show Path File
OpenFileDialog^OpFile;
private: System::Void BtnShowPathFile_Click(System::Object^ sender, System::EventArgs^ e) {
OpFile=gcnew OpenFileDialog();
OpFile->ShowDialog();
lblPathFile->Text="Path File : "+OpFile->FileName;
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Show Path File";
this->BackColor=Color::Yellow;
this->FormBorderStyle=Windows::Forms::FormBorderStyle::FixedToolWindow;
lblPathFile->Text="Path File : ";
}
};
}
Open ColorDialog

#pragma once
namespace My36 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::ColorDialog^ ColorDialog;
protected:
private: System::Windows::Forms::Button^ BtnOpenColorDialog;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->ColorDialog = (gcnew System::Windows::Forms::ColorDialog());
this->BtnOpenColorDialog = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// BtnOpenColorDialog
//
this->BtnOpenColorDialog->Location = System::Drawing::Point(13, 16);
this->BtnOpenColorDialog->Name = L"BtnOpenColorDialog";
this->BtnOpenColorDialog->Size = System::Drawing::Size(267, 46);
this->BtnOpenColorDialog->TabIndex = 0;
this->BtnOpenColorDialog->Text = L"Open ColorDialog";
this->BtnOpenColorDialog->UseVisualStyleBackColor = true;
this->BtnOpenColorDialog->Click += gcnew System::EventHandler(this, &Form1::BtnOpenColorDialog_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 75);
this->Controls->Add(this->BtnOpenColorDialog);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Open ColorDialog
private: System::Void BtnOpenColorDialog_Click(System::Object^ sender, System::EventArgs^ e) {
ColorDialog->AllowFullOpen=true;
ColorDialog->AnyColor=true;
if(ColorDialog->ShowDialog()==Windows::Forms::DialogResult::OK)
{
this->BackColor=ColorDialog->Color;
}
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Open ColorDialog";
this->MaximizeBox=false;
}
};
}
Show Time And Date

#pragma once
namespace My35 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnShowTimeAndDate;
private: System::Windows::Forms::Timer^ t;
private: System::ComponentModel::IContainer^ components;
protected:
protected:
private:
///
/// Required designer variable.
///
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
this->BtnShowTimeAndDate = (gcnew System::Windows::Forms::Button());
this->t = (gcnew System::Windows::Forms::Timer(this->components));
this->SuspendLayout();
//
// BtnShowTimeAndDate
//
this->BtnShowTimeAndDate->Location = System::Drawing::Point(15, 12);
this->BtnShowTimeAndDate->Name = L"BtnShowTimeAndDate";
this->BtnShowTimeAndDate->Size = System::Drawing::Size(321, 68);
this->BtnShowTimeAndDate->TabIndex = 0;
this->BtnShowTimeAndDate->Text = L"Show Time And Date";
this->BtnShowTimeAndDate->UseVisualStyleBackColor = true;
this->BtnShowTimeAndDate->Click += gcnew System::EventHandler(this, &Form1::BtnShowTimeAndDate_Click);
//
// t
//
this->t->Interval = 1;
this->t->Tick += gcnew System::EventHandler(this, &Form1::t_Tick);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(348, 92);
this->Controls->Add(this->BtnShowTimeAndDate);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Show Time And Date
String^ShTimeAndDate;
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Show Time And Date";
this->MaximizeBox=false;
this->BackColor=Color::PaleGoldenrod;
BtnShowTimeAndDate->BackColor=Color::Red;
BtnShowTimeAndDate->ForeColor=Color::White;
}
private: System::Void BtnShowTimeAndDate_Click(System::Object^ sender, System::EventArgs^ e) {
t->Enabled=true;
}
private: System::Void t_Tick(System::Object^ sender, System::EventArgs^ e) {
ShTimeAndDate=System::DateTime::Now.ToString();
this->Text=ShTimeAndDate;
}
};
}
Remove Items In ListBox

#pragma once
namespace My34 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::ListBox^ lst;
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->lst = (gcnew System::Windows::Forms::ListBox());
this->SuspendLayout();
//
// lst
//
this->lst->FormattingEnabled = true;
this->lst->Items->AddRange(gcnew cli::array<>(8) {L"Item 1", L"Item 2", L"Item 3", L"Item 4", L"Item 5",
L"Item 6", L"Item 7", L"Item 8"});
this->lst->Location = System::Drawing::Point(8, 10);
this->lst->Name = L"lst";
this->lst->Size = System::Drawing::Size(271, 121);
this->lst->TabIndex = 0;
this->lst->DoubleClick += gcnew System::EventHandler(this, &Form1::lst_DoubleClick);
this->lst->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::lst_SelectedIndexChanged);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 141);
this->Controls->Add(this->lst);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Remove Items In ListBox
private: System::Void lst_DoubleClick(System::Object^ sender, System::EventArgs^ e) {
this->Text=lst->Text;
lst->Items->RemoveAt(lst->SelectedIndex);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Romove Items In ListBox";
this->MaximizeBox=false;
}
private: System::Void lst_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
this->Text=lst->Text;
}
};
}
Select Items in ListBox

#pragma once
namespace My33 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::ListBox^ lst;
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->lst = (gcnew System::Windows::Forms::ListBox());
this->SuspendLayout();
//
// lst
//
this->lst->FormattingEnabled = true;
this->lst->Items->AddRange(gcnew cli::array<>(8) {L"Item 1", L"Item 2", L"Item 3", L"Item 4", L"Item 5",
L"Item 6", L"Item 7", L"Item 8"});
this->lst->Location = System::Drawing::Point(12, 13);
this->lst->Name = L"lst";
this->lst->Size = System::Drawing::Size(266, 121);
this->lst->TabIndex = 0;
this->lst->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::lst_SelectedIndexChanged);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 144);
this->Controls->Add(this->lst);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Select Items in ListBox
private: System::Void lst_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) {
this->Text=lst->Text;
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Select Items In ListBox";
this->MaximizeBox=false;
}
};
}
Add Items In ListBox

#pragma once
namespace My32 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::ListBox^ lstAddItems;
protected:
private: System::Windows::Forms::TextBox^ txtAdd;
private: System::Windows::Forms::Button^ BtnAdd;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->lstAddItems = (gcnew System::Windows::Forms::ListBox());
this->txtAdd = (gcnew System::Windows::Forms::TextBox());
this->BtnAdd = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// lstAddItems
//
this->lstAddItems->FormattingEnabled = true;
this->lstAddItems->Location = System::Drawing::Point(12, 14);
this->lstAddItems->Name = L"lstAddItems";
this->lstAddItems->Size = System::Drawing::Size(268, 199);
this->lstAddItems->TabIndex = 0;
//
// txtAdd
//
this->txtAdd->Location = System::Drawing::Point(14, 220);
this->txtAdd->Name = L"txtAdd";
this->txtAdd->Size = System::Drawing::Size(265, 20);
this->txtAdd->TabIndex = 1;
//
// BtnAdd
//
this->BtnAdd->Location = System::Drawing::Point(16, 251);
this->BtnAdd->Name = L"BtnAdd";
this->BtnAdd->Size = System::Drawing::Size(262, 27);
this->BtnAdd->TabIndex = 2;
this->BtnAdd->Text = L"Add to List";
this->BtnAdd->UseVisualStyleBackColor = true;
this->BtnAdd->Click += gcnew System::EventHandler(this, &Form1::BtnAdd_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(289, 285);
this->Controls->Add(this->BtnAdd);
this->Controls->Add(this->txtAdd);
this->Controls->Add(this->lstAddItems);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//Add Items In ListBox
private: System::Void BtnAdd_Click(System::Object^ sender, System::EventArgs^ e) {
lstAddItems->Items->Add(txtAdd->Text);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Add Items in ListBox";
this->MaximizeBox=false;
txtAdd->Text="Add Items";
}
};
}
Draw Animation Line

#pragma once
namespace My31 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Timer^ t;
private: System::Windows::Forms::Button^ BtnStart;
protected:
private: System::ComponentModel::IContainer^ components;
private:
///
/// Required designer variable.
///
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
this->t = (gcnew System::Windows::Forms::Timer(this->components));
this->BtnStart = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// t
//
this->t->Interval = 1;
this->t->Tick += gcnew System::EventHandler(this, &Form1::t_Tick);
//
// BtnStart
//
this->BtnStart->Location = System::Drawing::Point(12, 12);
this->BtnStart->Name = L"BtnStart";
this->BtnStart->Size = System::Drawing::Size(111, 27);
this->BtnStart->TabIndex = 0;
this->BtnStart->Text = L"Start";
this->BtnStart->UseVisualStyleBackColor = true;
this->BtnStart->Click += gcnew System::EventHandler(this, &Form1::BtnStart_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Controls->Add(this->BtnStart);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Draw Animation Line
Graphics^G;
Pen^HPen;
Pen^HPen2;
int cY1;
int cY2;
private: System::Void t_Tick(System::Object^ sender, System::EventArgs^ e) {
HPen=gcnew Pen(Color::Yellow,1);
HPen2=gcnew Pen(Color::Blue,2);
HPen->DashStyle=System::Drawing::Drawing2D::DashStyle::DashDot;
HPen2->DashStyle=System::Drawing::Drawing2D::DashStyle::DashDotDot;
cY1++;
cY2--;
G->DrawLine(HPen,0,cY1,500,cY1);
G->DrawLine(HPen2,500,cY2,this->Width,cY2);
}
private: System::Void BtnStart_Click(System::Object^ sender, System::EventArgs^ e) {
G->Clear(this->BackColor);
cY2=this->Height;
cY1=0;
t->Enabled=true;
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->BackColor=Color::Black;
this->Text="Draw Animation Line";
this->FormBorderStyle=Windows::Forms::FormBorderStyle::FixedToolWindow;
this->Left=0;
this->Top=0;
this->Width=Screen::PrimaryScreen->WorkingArea.Width;
this->Height=Screen::PrimaryScreen->WorkingArea.Height;
G=this->CreateGraphics();
}
};
}
DrawLine With Mouse

#pragma once
namespace My30 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(528, 326);
this->Name = L"Form1";
this->Text = L"Form1";
this->MouseUp += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::Form1_MouseUp);
this->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::Form1_MouseMove);
this->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::Form1_MouseDown);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//DrawLine With Mouse
Graphics^G;
Pen^HPen;
bool BCheck;
int TmpX;
int TmpY;
private: System::Void Form1_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
BCheck=true;
TmpX=e->X;
TmpY=e->Y;
}
private: System::Void Form1_MouseMove(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
if(BCheck==true)
{
if(e->Button==Windows::Forms::MouseButtons::Left)
{
G->Clear(this->BackColor);
G->DrawLine(HPen,TmpX,TmpY,e->X,e->Y);
}
}
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
G=this->CreateGraphics();
HPen=gcnew Pen(Color::Yellow,1);
HPen->DashStyle=System::Drawing::Drawing2D::DashStyle::Dot;
this->BackColor=Color::Green;
}
private: System::Void Form1_MouseUp(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
BCheck=false;
}
};
}
Random RGB Color

#pragma once
namespace My29 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnShowRGB;
protected:
private: System::Windows::Forms::Button^ BRed;
private: System::Windows::Forms::Button^ BtnGreen;
private: System::Windows::Forms::Button^ BtnBlue;
private: System::Windows::Forms::PictureBox^ PctResult;
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnShowRGB = (gcnew System::Windows::Forms::Button());
this->BRed = (gcnew System::Windows::Forms::Button());
this->BtnGreen = (gcnew System::Windows::Forms::Button());
this->BtnBlue = (gcnew System::Windows::Forms::Button());
this->PctResult = (gcnew System::Windows::Forms::PictureBox());
(cli::safe_cast
this->SuspendLayout();
//
// BtnShowRGB
//
this->BtnShowRGB->Location = System::Drawing::Point(12, 185);
this->BtnShowRGB->Name = L"BtnShowRGB";
this->BtnShowRGB->Size = System::Drawing::Size(145, 40);
this->BtnShowRGB->TabIndex = 0;
this->BtnShowRGB->Text = L"Show ColorRGB";
this->BtnShowRGB->UseVisualStyleBackColor = true;
this->BtnShowRGB->Click += gcnew System::EventHandler(this, &Form1::BtnRandomRGB_Click);
//
// BRed
//
this->BRed->Location = System::Drawing::Point(12, 12);
this->BRed->Name = L"BRed";
this->BRed->Size = System::Drawing::Size(145, 42);
this->BRed->TabIndex = 1;
this->BRed->Text = L"Red";
this->BRed->UseVisualStyleBackColor = true;
this->BRed->Click += gcnew System::EventHandler(this, &Form1::BRed_Click);
//
// BtnGreen
//
this->BtnGreen->Location = System::Drawing::Point(12, 60);
this->BtnGreen->Name = L"BtnGreen";
this->BtnGreen->Size = System::Drawing::Size(145, 42);
this->BtnGreen->TabIndex = 2;
this->BtnGreen->Text = L"Green";
this->BtnGreen->UseVisualStyleBackColor = true;
this->BtnGreen->Click += gcnew System::EventHandler(this, &Form1::BtnGreen_Click);
//
// BtnBlue
//
this->BtnBlue->Location = System::Drawing::Point(12, 108);
this->BtnBlue->Name = L"BtnBlue";
this->BtnBlue->Size = System::Drawing::Size(145, 42);
this->BtnBlue->TabIndex = 3;
this->BtnBlue->Text = L"Blue";
this->BtnBlue->UseVisualStyleBackColor = true;
this->BtnBlue->Click += gcnew System::EventHandler(this, &Form1::BtnBlue_Click);
//
// PctResult
//
this->PctResult->Location = System::Drawing::Point(168, 11);
this->PctResult->Name = L"PctResult";
this->PctResult->Size = System::Drawing::Size(369, 213);
this->PctResult->TabIndex = 4;
this->PctResult->TabStop = false;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(550, 236);
this->Controls->Add(this->PctResult);
this->Controls->Add(this->BtnBlue);
this->Controls->Add(this->BtnGreen);
this->Controls->Add(this->BRed);
this->Controls->Add(this->BtnShowRGB);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
(cli::safe_cast
this->ResumeLayout(false);
}
#pragma endregion
//Random RGB Color
int rRed;
int rGreen;
int rBlue;
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->MaximizeBox=false;
this->BackColor=Color::Gray;
this->Text="Random RGB Color = Red : "+rRed+" Green : "+rGreen+
" Blue : "+rBlue;
PctResult->BackColor=Color::Black;
PctResult->BorderStyle=Windows::Forms::BorderStyle::Fixed3D;
}
private: System::Void BtnRandomRGB_Click(System::Object^ sender, System::EventArgs^ e) {
PctResult->BackColor=Color::FromArgb(rRed,rGreen,rBlue);
this->Text="Random RGB Color = Red : "+rRed+" Green : "+rGreen+
" Blue : "+rBlue;
}
private: System::Void BRed_Click(System::Object^ sender, System::EventArgs^ e) {
rRed=Random().Next(255);
}
private: System::Void BtnGreen_Click(System::Object^ sender, System::EventArgs^ e) {
rGreen=Random().Next(255);
}
private: System::Void BtnBlue_Click(System::Object^ sender, System::EventArgs^ e) {
rBlue=Random().Next(255);
}
};
}
Get Color Pixel on Image
#pragma once
namespace My28 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::PictureBox^ PctGetColor;
protected:
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->PctGetColor = (gcnew System::Windows::Forms::PictureBox());
(cli::safe_cast
this->SuspendLayout();
//
// PctGetColor
//
this->PctGetColor->Location = System::Drawing::Point(316, 1);
this->PctGetColor->Name = L"PctGetColor";
this->PctGetColor->Size = System::Drawing::Size(60, 44);
this->PctGetColor->TabIndex = 0;
this->PctGetColor->TabStop = false;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(377, 322);
this->Controls->Add(this->PctGetColor);
this->Name = L"Form1";
this->Text = L"Form1";
this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::Form1_Paint);
this->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::Form1_MouseDown);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
(cli::safe_cast
this->ResumeLayout(false);
}
#pragma endregion
//Get Color Pixel on Image
Graphics^GetColor_Graphics;
Bitmap^GetColor_Bitmap;
Color KColor;
private: System::Void Form1_MouseDown(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
int cX;
int cY;
cX=e->X;
cY=e->Y;
if(e->Button==Windows::Forms::MouseButtons::Left)
{
KColor=GetColor_Bitmap->GetPixel(cX,cY);
PctGetColor->BackColor=KColor;
this->Text="Current X : "+cX+" Current Y : "+cY;
}
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
PctGetColor->BorderStyle=Windows::Forms::BorderStyle::Fixed3D;
}
private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
GetColor_Graphics=this->CreateGraphics();
GetColor_Bitmap=gcnew Bitmap("C:\\Flower.Bmp");
GetColor_Graphics->DrawImage(GetColor_Bitmap,0,0,400,400);
}
};
}
Gradient

#pragma once
namespace My27 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnGradient;
protected:
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnGradient = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// BtnGradient
//
this->BtnGradient->Location = System::Drawing::Point(105, 279);
this->BtnGradient->Name = L"BtnGradient";
this->BtnGradient->Size = System::Drawing::Size(123, 43);
this->BtnGradient->TabIndex = 0;
this->BtnGradient->Text = L"Gradient";
this->BtnGradient->UseVisualStyleBackColor = true;
this->BtnGradient->Click += gcnew System::EventHandler(this, &Form1::BtnGradient_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(306, 335);
this->Controls->Add(this->BtnGradient);
this->Name = L"Form1";
this->Text = L"Form1";
this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::Form1_Paint);
this->ResumeLayout(false);
}
#pragma endregion
//Gradient
private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
}
private: System::Void BtnGradient_Click(System::Object^ sender, System::EventArgs^ e) {
Graphics^g;
g=this->CreateGraphics();
System::Drawing::Drawing2D::LinearGradientBrush^b;
b=gcnew System::Drawing::Drawing2D::LinearGradientBrush(ClientRectangle,Color::Red,Color::Yellow,System::Drawing::Drawing2D::LinearGradientMode::BackwardDiagonal);
g->FillRectangle(b,Rectangle(0,0,this->Width,this->Height));
}
};
}
Random

#pragma once
namespace My26 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnRandom;
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnRandom = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// BtnRandom
//
this->BtnRandom->Location = System::Drawing::Point(31, 22);
this->BtnRandom->Name = L"BtnRandom";
this->BtnRandom->Size = System::Drawing::Size(190, 56);
this->BtnRandom->TabIndex = 0;
this->BtnRandom->Text = L"Random";
this->BtnRandom->UseVisualStyleBackColor = true;
this->BtnRandom->Click += gcnew System::EventHandler(this, &Form1::BtnRandom_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(237, 98);
this->Controls->Add(this->BtnRandom);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Random
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->BackColor=Color::BlueViolet;
this->MaximizeBox=false;
this->Text="Random : ";
BtnRandom->BackColor=Color::Black;
BtnRandom->ForeColor=Color::White;
}
private: System::Void BtnRandom_Click(System::Object^ sender, System::EventArgs^ e) {
int i;
i=Random().Next(100);
this->Text="Random : "+i.ToString();
}
};
}
DrawEllipse

#pragma once
namespace My15 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::Form1_Paint);
this->ResumeLayout(false);
}
#pragma endregion
//DrawEllipse
private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
Graphics^DrawText_Graphics;
Brushes^HBrush;
Pen^HPen;
DrawText_Graphics=this->CreateGraphics();
HPen=gcnew Pen(Color::White,4);
HPen->DashStyle=Drawing2D::DashStyle::Dot;
DrawText_Graphics->DrawEllipse(HPen,10,10,270,240);
this->Text="DrawEllipse";
this->BackColor=Color::Blue;
}
};
}
FontDialog

#pragma once
namespace My25 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnOpenFont;
private: System::Windows::Forms::TextBox^ t;
private: System::Windows::Forms::FontDialog^ f;
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnOpenFont = (gcnew System::Windows::Forms::Button());
this->t = (gcnew System::Windows::Forms::TextBox());
this->f = (gcnew System::Windows::Forms::FontDialog());
this->SuspendLayout();
//
// BtnOpenFont
//
this->BtnOpenFont->Location = System::Drawing::Point(16, 209);
this->BtnOpenFont->Name = L"BtnOpenFont";
this->BtnOpenFont->Size = System::Drawing::Size(264, 49);
this->BtnOpenFont->TabIndex = 0;
this->BtnOpenFont->Text = L"Open Font";
this->BtnOpenFont->UseVisualStyleBackColor = true;
this->BtnOpenFont->Click += gcnew System::EventHandler(this, &Form1::BtnOpenFont_Click);
//
// t
//
this->t->Location = System::Drawing::Point(22, 12);
this->t->Multiline = true;
this->t->Name = L"t";
this->t->Size = System::Drawing::Size(258, 182);
this->t->TabIndex = 1;
this->t->Text = L"fdasfdasf";
//
// f
//
this->f->Apply += gcnew System::EventHandler(this, &Form1::f_Apply);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Controls->Add(this->t);
this->Controls->Add(this->BtnOpenFont);
this->Name = L"Form1";
this->Text = L"Form1";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//FontDialog
private: System::Void BtnOpenFont_Click(System::Object^ sender, System::EventArgs^ e) {
f->ShowApply=true;
f->ShowColor=true;
f->ShowEffects=true;
if(f->ShowDialog()==System::Windows::Forms::DialogResult::Cancel)
{
t->ResetForeColor();
t->ResetFont();
}else{
t->Font::set(f->Font::get());
t->ForeColor::set(f->Color::get());
}
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
}
private: System::Void f_Apply(System::Object^ sender, System::EventArgs^ e) {
t->Font::set(f->Font::get());
t->ForeColor::set(f->Color::get());
}
};
}
Move Character

#pragma once
namespace My24 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
protected:
private: System::ComponentModel::IContainer^ components;
private:
///
/// Required designer variable.
///
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(632, 584);
this->Name = L"Form1";
this->Text = L"Form1";
this->KeyDown += gcnew System::Windows::Forms::KeyEventHandler(this, &Form1::Form1_KeyDown);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Move Character
int Ch_X;
int Ch_Y;
Graphics^BoardGraphics;
Graphics^HandleToBoardGraphics;
Bitmap^BoardBmp;
Bitmap^Grass;
Bitmap^Floor;
void DrawCharacter(String^StrFilename,int ChX,int ChY)
{
BoardGraphics=this->CreateGraphics();
Grass=gcnew Bitmap(StrFilename);
BoardBmp=gcnew Bitmap("C:\\Bkg.Bmp");
Floor=gcnew Bitmap("C:\\Bkg.PNG");
Grass->MakeTransparent(Color::Black);
BoardBmp->MakeTransparent(Color::Black);
HandleToBoardGraphics=Graphics::FromImage(BoardBmp);
HandleToBoardGraphics->Clear(this->BackColor);
HandleToBoardGraphics->DrawImage(Floor,0,0,this->Width,this->Height);
HandleToBoardGraphics->DrawImage(Grass,ChX,ChY);
BoardGraphics->DrawImage(BoardBmp,0,0);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Move Character";
this->MaximizeBox=false;
}
private: System::Void Form1_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e) {
if(e->KeyCode==Windows::Forms::Keys::Down)
{
Ch_Y=Ch_Y+=10;
DrawCharacter("C:\\Character.Bmp",Ch_X,Ch_Y);
}
}
};
}
Draw Character

#pragma once
namespace My23 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
///
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::Form1_Paint);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Draw Character
private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
Graphics^G;
Bitmap^B;
B=gcnew Bitmap("C:\\Character.Bmp");
B->MakeTransparent(Color::Black);
G=this->CreateGraphics();
G->DrawImage(B,50,50);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Draw Character";
this->MaximizeBox=false;
}
};
}
Image Format
The executable image format is PE32+. Executable images (both DLLs and EXEs) are restricted to a maximum size of 2 gigabytes, so relative addressing with a 32-bit displacement can be used to address static image data. This data includes the import address table, string constants, static global data, and so on.
Visual C++ libraries are side-by-side assembliesVisual Studio 2005 installs Visual C++ libraries as shared side-by-side assemblies. By default, all applications built with Visual Studio 2005 are built as isolated applications with a manifest either embedded as a resource, or accompanying the final binary as an external file. In order to ensure that your Visual C++ application will run on a computer without Visual C++ installed, you may have to redistribute Visual Redistributing Visual C++ librariesThere are two recommended ways to redistribute Visual C++ DLLs. First, you can use Visual C++ Redistributable Merge Modules to install Visual C++ assemblies as shared side-by-side assemblies. Alternatively, you can install a particular Visual C++ assembly as a private assembly for the application using files provide in the Program Files\Microsoft Visual Studio 8\VC\Redist directory.
Note On Windows Server 2000, Windows 95 and Windows 98, the only recommended and supported way to redistribute Visual C++ libraries is by using Redistributable Merge Modules.
When installing Visual C++ assemblies using redistributable merge modules, the assemblies are deployed as shared side-by-side assemblies into the native assembly cache (WinSxS folder). Access to this folder requires that the installer application be run by a user with administrative rights.
If an installation is run by a user who does not have administrative rights, the installation fails to deploy the Visual C++ assemblies and the application will not run. Also, some products may allow installation on a per-user basis, but merge modules install libraries into shared locations and impact all users of the system. In both these and similar scenarios, the supported technique is to install the required assemblies as private side-by-side assemblies for a particular user's application.
With this technique, it is enough to copy a folder with DLLs and manifests for dependent assemblies to the application's local folder. The operating system's loader, when executing the application, still looks for dependent assemblies in the WinSxS folder first; however when a corresponding assembly cannot be found, the loader loads a private assembly from this sub-directory. More details on this can be found in Redistributing Visual C++ Files.
Manifest requiredIt is not supported to redistribute C/C++ applications that are built without a manifest. Visual C++ libraries cannot be used by C/C++ applications without a manifest binding the application to these library. All C/C++ programs built in Visual C++ 2005 have to include a manifest describing their dependencies on Visual C++ libraries. This is the default setup of projects in Visual Studio and the default behavior of the linker building the final binary from object code.
Applications that expect dependent DLLs to be present in either the application-local folder, or in a folder indicated by an environment variable may also be vulnerable to security-related exploits. It is also more difficult to service such applications after they have been deployed.
Prefer dynamic linking over static linkingIt is not recommended to redistribute C/C++ applications that statically link to Visual C++ libraries. It is often mistakenly assumed that by statically linking your program to Visual C++ libraries it is possible to significantly improve the performance of an application. However the impact on performance of dynamically loading Visual C++ libraries is insignificant in almost all cases. Furthermore, static linking does not allow for servicing the application and its dependent libraries by either the application's author or Microsoft. For example, consider an application that is statically linked to a particular library, running on a client computer with a new version of this library. The application still uses code from the previous version of this library, and does not benefit from library improvements, such as security enhancements. Authors of C/C++ applications are strongly advised to think through the servicing scenario before deciding to statically link to dependent libraries, and use dynamic linking whenever possible.
Visual C++ libraries are side-by-side assembliesVisual Studio 2005 installs Visual C++ libraries as shared side-by-side assemblies. By default, all applications built with Visual Studio 2005 are built as isolated applications with a manifest either embedded as a resource, or accompanying the final binary as an external file. In order to ensure that your Visual C++ application will run on a computer without Visual C++ installed, you may have to redistribute Visual Redistributing Visual C++ librariesThere are two recommended ways to redistribute Visual C++ DLLs. First, you can use Visual C++ Redistributable Merge Modules to install Visual C++ assemblies as shared side-by-side assemblies. Alternatively, you can install a particular Visual C++ assembly as a private assembly for the application using files provide in the Program Files\Microsoft Visual Studio 8\VC\Redist directory.
Note On Windows Server 2000, Windows 95 and Windows 98, the only recommended and supported way to redistribute Visual C++ libraries is by using Redistributable Merge Modules.
When installing Visual C++ assemblies using redistributable merge modules, the assemblies are deployed as shared side-by-side assemblies into the native assembly cache (WinSxS folder). Access to this folder requires that the installer application be run by a user with administrative rights.
If an installation is run by a user who does not have administrative rights, the installation fails to deploy the Visual C++ assemblies and the application will not run. Also, some products may allow installation on a per-user basis, but merge modules install libraries into shared locations and impact all users of the system. In both these and similar scenarios, the supported technique is to install the required assemblies as private side-by-side assemblies for a particular user's application.
With this technique, it is enough to copy a folder with DLLs and manifests for dependent assemblies to the application's local folder. The operating system's loader, when executing the application, still looks for dependent assemblies in the WinSxS folder first; however when a corresponding assembly cannot be found, the loader loads a private assembly from this sub-directory. More details on this can be found in Redistributing Visual C++ Files.
Manifest requiredIt is not supported to redistribute C/C++ applications that are built without a manifest. Visual C++ libraries cannot be used by C/C++ applications without a manifest binding the application to these library. All C/C++ programs built in Visual C++ 2005 have to include a manifest describing their dependencies on Visual C++ libraries. This is the default setup of projects in Visual Studio and the default behavior of the linker building the final binary from object code.
Applications that expect dependent DLLs to be present in either the application-local folder, or in a folder indicated by an environment variable may also be vulnerable to security-related exploits. It is also more difficult to service such applications after they have been deployed.
Prefer dynamic linking over static linkingIt is not recommended to redistribute C/C++ applications that statically link to Visual C++ libraries. It is often mistakenly assumed that by statically linking your program to Visual C++ libraries it is possible to significantly improve the performance of an application. However the impact on performance of dynamically loading Visual C++ libraries is insignificant in almost all cases. Furthermore, static linking does not allow for servicing the application and its dependent libraries by either the application's author or Microsoft. For example, consider an application that is statically linked to a particular library, running on a client computer with a new version of this library. The application still uses code from the previous version of this library, and does not benefit from library improvements, such as security enhancements. Authors of C/C++ applications are strongly advised to think through the servicing scenario before deciding to statically link to dependent libraries, and use dynamic linking whenever possible.
Using FromArgb In Class Color

#pragma once
namespace My22 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnRed;
protected:
private: System::Windows::Forms::Button^ BtnGreen;
private: System::Windows::Forms::Button^ BtnBlue;
private: System::Windows::Forms::Button^ BtnMix;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnRed = (gcnew System::Windows::Forms::Button());
this->BtnGreen = (gcnew System::Windows::Forms::Button());
this->BtnBlue = (gcnew System::Windows::Forms::Button());
this->BtnMix = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// BtnRed
//
this->BtnRed->Location = System::Drawing::Point(12, 22);
this->BtnRed->Name = L"BtnRed";
this->BtnRed->Size = System::Drawing::Size(66, 35);
this->BtnRed->TabIndex = 0;
this->BtnRed->Text = L"Red";
this->BtnRed->UseVisualStyleBackColor = true;
this->BtnRed->Click += gcnew System::EventHandler(this, &Form1::BtnRed_Click);
//
// BtnGreen
//
this->BtnGreen->Location = System::Drawing::Point(84, 22);
this->BtnGreen->Name = L"BtnGreen";
this->BtnGreen->Size = System::Drawing::Size(66, 35);
this->BtnGreen->TabIndex = 1;
this->BtnGreen->Text = L"Green";
this->BtnGreen->UseVisualStyleBackColor = true;
this->BtnGreen->Click += gcnew System::EventHandler(this, &Form1::BtnGreen_Click);
//
// BtnBlue
//
this->BtnBlue->Location = System::Drawing::Point(156, 22);
this->BtnBlue->Name = L"BtnBlue";
this->BtnBlue->Size = System::Drawing::Size(66, 35);
this->BtnBlue->TabIndex = 2;
this->BtnBlue->Text = L"Blue";
this->BtnBlue->UseVisualStyleBackColor = true;
this->BtnBlue->Click += gcnew System::EventHandler(this, &Form1::BtnBlue_Click);
//
// BtnMix
//
this->BtnMix->Location = System::Drawing::Point(228, 22);
this->BtnMix->Name = L"BtnMix";
this->BtnMix->Size = System::Drawing::Size(66, 35);
this->BtnMix->TabIndex = 3;
this->BtnMix->Text = L"Mix Color";
this->BtnMix->UseVisualStyleBackColor = true;
this->BtnMix->Click += gcnew System::EventHandler(this, &Form1::BtnMix_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(304, 78);
this->Controls->Add(this->BtnMix);
this->Controls->Add(this->BtnBlue);
this->Controls->Add(this->BtnGreen);
this->Controls->Add(this->BtnRed);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Using FromArgb In Class Color
private: System::Void BtnRed_Click(System::Object^ sender, System::EventArgs^ e) {
BtnRed->BackColor=Color::FromArgb(255,0,0);
}
private: System::Void BtnGreen_Click(System::Object^ sender, System::EventArgs^ e) {
BtnGreen->BackColor=Color::FromArgb(0,255,0);
}
private: System::Void BtnBlue_Click(System::Object^ sender, System::EventArgs^ e) {
BtnBlue->BackColor=Color::FromArgb(0,0,255);
}
private: System::Void BtnMix_Click(System::Object^ sender, System::EventArgs^ e) {
BtnMix->BackColor=Color::FromArgb(180,150,96);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Using FromArgb In Class Color";
this->MaximizeBox=false;
this->BackColor=Color::Yellow;
}
};
}
Open Bitmap File

#pragma once
namespace My21 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnOpenBitmap;
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnOpenBitmap = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// BtnOpenBitmap
//
this->BtnOpenBitmap->Location = System::Drawing::Point(12, 205);
this->BtnOpenBitmap->Name = L"BtnOpenBitmap";
this->BtnOpenBitmap->Size = System::Drawing::Size(268, 53);
this->BtnOpenBitmap->TabIndex = 0;
this->BtnOpenBitmap->Text = L"Open Bitmap";
this->BtnOpenBitmap->UseVisualStyleBackColor = true;
this->BtnOpenBitmap->Click += gcnew System::EventHandler(this, &Form1::BtnOpenBitmap_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 270);
this->Controls->Add(this->BtnOpenBitmap);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load_1);
this->ResumeLayout(false);
}
#pragma endregion
//Open Bitmap File
String^StrFilename;
private: System::Void BtnOpenBitmap_Click(System::Object^ sender, System::EventArgs^ e) {
OpenFileDialog^OpenBitmap;
OpenBitmap=gcnew OpenFileDialog();
OpenBitmap->Filter="*.bmp*.bmp";
OpenBitmap->ShowDialog();
StrFilename=OpenBitmap->FileName;
this->Text=StrFilename;
Graphics^OpenBitmap_Graphics;
Bitmap^OpenBitmap_Bitmap;
OpenBitmap_Bitmap=gcnew Bitmap(StrFilename);
OpenBitmap_Graphics=this->CreateGraphics();
OpenBitmap_Graphics->DrawImage(OpenBitmap_Bitmap,0,0);
}
private: System::Void Form1_Load_1(System::Object^ sender, System::EventArgs^ e) {
this->Text="OpenFileDialog";
this->BackColor=Color::Bisque;
this->MaximizeBox=false;
BtnOpenBitmap->BackColor=Color::Red;
}
};
}
OpenFileDialog

#pragma once
namespace My20 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnOpenDialog;
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnOpenDialog = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// BtnOpenDialog
//
this->BtnOpenDialog->Location = System::Drawing::Point(28, 173);
this->BtnOpenDialog->Name = L"BtnOpenDialog";
this->BtnOpenDialog->Size = System::Drawing::Size(232, 67);
this->BtnOpenDialog->TabIndex = 0;
this->BtnOpenDialog->Text = L"Open Dialog";
this->BtnOpenDialog->UseVisualStyleBackColor = true;
this->BtnOpenDialog->Click += gcnew System::EventHandler(this, &Form1::BtnOpenDialog_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Controls->Add(this->BtnOpenDialog);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//OpenFileDialog
private: System::Void BtnOpenDialog_Click(System::Object^ sender, System::EventArgs^ e) {
OpenFileDialog^op;
op=gcnew OpenFileDialog();
op->ShowDialog();
this->Text=op->FileName;
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="OpenFileDialog";
this->BackColor=Color::Azure;
this->MaximizeBox=false;
}
};
}
Draw FillRectangle

#pragma once
namespace My19 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(347, 319);
this->Name = L"Form1";
this->Text = L"Form1";
this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::Form1_Paint);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Draw FillRectangle
private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
Graphics^g;
g=this->CreateGraphics();
g->FillRectangle(Brushes::Blue,10,10,330,300);
g->FillRectangle(Brushes::Yellow,50,50,250,230);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Draw FillRectangle";
this->BackColor=Color::Red;
this->MaximizeBox=false;
}
};
}
StretchImage

#pragma once
namespace My18 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(672, 544);
this->Name = L"Form1";
this->Text = L"Form1";
this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::Form1_Paint);
this->Resize += gcnew System::EventHandler(this, &Form1::Form1_Resize);
this->ResumeLayout(false);
}
#pragma endregion
//StretchImage
Graphics^G;
Bitmap^B;
void StretchImage()
{
G=this->CreateGraphics();
B=gcnew Bitmap("C:\\Flower.Bmp");
G->DrawImage(B,0,0,this->Width,this->Height);
}
private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
StretchImage();
}
private: System::Void Form1_Resize(System::Object^ sender, System::EventArgs^ e) {
StretchImage();
}
};
}
Rotate Image

#pragma once
namespace My17 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnShowImage;
protected:
private: System::Windows::Forms::Button^ BtnRotateImage;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnShowImage = (gcnew System::Windows::Forms::Button());
this->BtnRotateImage = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// BtnShowImage
//
this->BtnShowImage->Location = System::Drawing::Point(12, 386);
this->BtnShowImage->Name = L"BtnShowImage";
this->BtnShowImage->Size = System::Drawing::Size(240, 42);
this->BtnShowImage->TabIndex = 0;
this->BtnShowImage->Text = L"Show Image";
this->BtnShowImage->UseVisualStyleBackColor = true;
this->BtnShowImage->Click += gcnew System::EventHandler(this, &Form1::BtnShowImage_Click);
//
// BtnRotateImage
//
this->BtnRotateImage->Location = System::Drawing::Point(258, 386);
this->BtnRotateImage->Name = L"BtnRotateImage";
this->BtnRotateImage->Size = System::Drawing::Size(240, 42);
this->BtnRotateImage->TabIndex = 1;
this->BtnRotateImage->Text = L"RotateImage";
this->BtnRotateImage->UseVisualStyleBackColor = true;
this->BtnRotateImage->Click += gcnew System::EventHandler(this, &Form1::BtnRotateImage_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(506, 440);
this->Controls->Add(this->BtnRotateImage);
this->Controls->Add(this->BtnShowImage);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Rotate Image
Graphics^RotateImage_Graphics;
Bitmap^RotateImage_Bitmap;
void cDrawImage()
{
RotateImage_Bitmap=gcnew Bitmap("C:\\Flower.Bmp");
RotateImage_Graphics->DrawImage(RotateImage_Bitmap,100,50,300,300);
}
private: System::Void BtnShowImage_Click(System::Object^ sender, System::EventArgs^ e) {
cDrawImage();
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
RotateImage_Graphics=this->CreateGraphics();
this->Text="RotateImage";
this->MaximizeBox=false;
this->BackColor=Color::Red;
}
private: System::Void BtnRotateImage_Click(System::Object^ sender, System::EventArgs^ e) {
int cAngle;
cAngle+=5;
RotateImage_Graphics->RotateTransform(cAngle);
RotateImage_Graphics->Clear(this->BackColor);
cDrawImage();
}
};
}
Show Image On Form

#pragma once
namespace My16 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnShowImage;
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnShowImage = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// BtnShowImage
//
this->BtnShowImage->Location = System::Drawing::Point(12, 270);
this->BtnShowImage->Name = L"BtnShowImage";
this->BtnShowImage->Size = System::Drawing::Size(321, 38);
this->BtnShowImage->TabIndex = 0;
this->BtnShowImage->Text = L"Show Image";
this->BtnShowImage->UseVisualStyleBackColor = true;
this->BtnShowImage->Click += gcnew System::EventHandler(this, &Form1::BtnShowImage_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(345, 320);
this->Controls->Add(this->BtnShowImage);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Show Image On Form
private: System::Void BtnShowImage_Click(System::Object^ sender, System::EventArgs^ e) {
Graphics^ShowImage_Graphics;
Bitmap^ShowImage_Bitmap;
ShowImage_Graphics=this->CreateGraphics();
ShowImage_Bitmap=gcnew Bitmap("C:\\Flower.Bmp");
ShowImage_Graphics->DrawImage(ShowImage_Bitmap,0,0,350,250);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->BackColor=Color::AliceBlue;
this->Text="Show Image On Form";
this->MaximizeBox=false;
}
};
}
FillPie

#pragma once
namespace My14 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(158, 142);
this->Name = L"Form1";
this->Text = L"Form1";
this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::Form1_Paint);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//FillPie
private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
Graphics^g;
Brushes^HBrush;
g=this->CreateGraphics();
g->FillPie(HBrush->Coral,10,10,100,100,160,200);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="DrawPie";
this->BackColor=System::Drawing::Color::Blue;
this->MaximizeBox=false;
}
};
}
Move File

#pragma once
namespace My13 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
///
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnCreateFile;
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnCreateFile = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// BtnCreateFile
//
this->BtnCreateFile->Location = System::Drawing::Point(12, 12);
this->BtnCreateFile->Name = L"BtnCreateFile";
this->BtnCreateFile->Size = System::Drawing::Size(551, 61);
this->BtnCreateFile->TabIndex = 0;
this->BtnCreateFile->Text = L"Create File";
this->BtnCreateFile->UseVisualStyleBackColor = true;
this->BtnCreateFile->Click += gcnew System::EventHandler(this, &Form1::BtnCreateFile_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(575, 90);
this->Controls->Add(this->BtnCreateFile);
this->Name = L"Form1";
this->Text = L"Form1";
this->ResumeLayout(false);
}
#pragma endregion
//Move File
private: System::Void BtnCreateFile_Click(System::Object^ sender, System::EventArgs^ e) {
File::Move("D:\\01.Bmp","D:\\Download\\01.BMP");
MessageBox::Show("Move File Completed","Move File");
}
};
}
Copy File

#pragma once
namespace My12 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO;
///
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnCopyFile;
private: System::Windows::Forms::Label^ lblSource;
private: System::Windows::Forms::Label^ lblDes;
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnCopyFile = (gcnew System::Windows::Forms::Button());
this->lblSource = (gcnew System::Windows::Forms::Label());
this->lblDes = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// BtnCopyFile
//
this->BtnCopyFile->Location = System::Drawing::Point(12, 118);
this->BtnCopyFile->Name = L"BtnCopyFile";
this->BtnCopyFile->Size = System::Drawing::Size(524, 33);
this->BtnCopyFile->TabIndex = 0;
this->BtnCopyFile->Text = L"Copy File";
this->BtnCopyFile->UseVisualStyleBackColor = true;
this->BtnCopyFile->Click += gcnew System::EventHandler(this, &Form1::BtnCopyFile_Click);
//
// lblSource
//
this->lblSource->AutoSize = true;
this->lblSource->Location = System::Drawing::Point(14, 21);
this->lblSource->Name = L"lblSource";
this->lblSource->Size = System::Drawing::Size(66, 13);
this->lblSource->TabIndex = 1;
this->lblSource->Text = L"Source File :";
//
// lblDes
//
this->lblDes->AutoSize = true;
this->lblDes->Location = System::Drawing::Point(14, 75);
this->lblDes->Name = L"lblDes";
this->lblDes->Size = System::Drawing::Size(85, 13);
this->lblDes->TabIndex = 2;
this->lblDes->Text = L"Destination File :";
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(548, 163);
this->Controls->Add(this->lblDes);
this->Controls->Add(this->lblSource);
this->Controls->Add(this->BtnCopyFile);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//Copy File
String^Source_File;
String^Destination_File;
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
Source_File= "C:\\01.Bmp";
Destination_File ="D:\\01.Bmp";
lblSource->Text="Source File : "+Source_File;
lblDes->Text="Destination File : "+Destination_File;
}
private: System::Void BtnCopyFile_Click(System::Object^ sender, System::EventArgs^ e) {
File::Copy(Source_File,Destination_File);
MessageBox::Show("Copy Completed","Copy File",System::Windows::Forms::MessageBoxButtons::OK,
System::Windows::Forms::MessageBoxIcon::Information);
}
};
}
Calculation Square

#pragma once
namespace My11 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ BtnResult;
private: System::Windows::Forms::TextBox^ txtSide2;
protected:
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::PictureBox^ pctResult;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::Label^ label3;
private: System::Windows::Forms::TextBox^ txtSide1;
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->BtnResult = (gcnew System::Windows::Forms::Button());
this->txtSide2 = (gcnew System::Windows::Forms::TextBox());
this->label1 = (gcnew System::Windows::Forms::Label());
this->pctResult = (gcnew System::Windows::Forms::PictureBox());
this->label2 = (gcnew System::Windows::Forms::Label());
this->label3 = (gcnew System::Windows::Forms::Label());
this->txtSide1 = (gcnew System::Windows::Forms::TextBox());
(cli::safe_cast
this->SuspendLayout();
//
// BtnResult
//
this->BtnResult->Location = System::Drawing::Point(61, 166);
this->BtnResult->Name = L"BtnResult";
this->BtnResult->Size = System::Drawing::Size(238, 92);
this->BtnResult->TabIndex = 0;
this->BtnResult->Text = L"Show Result";
this->BtnResult->UseVisualStyleBackColor = true;
this->BtnResult->Click += gcnew System::EventHandler(this, &Form1::BtnResult_Click);
//
// txtSide2
//
this->txtSide2->Location = System::Drawing::Point(61, 109);
this->txtSide2->Name = L"txtSide2";
this->txtSide2->Size = System::Drawing::Size(238, 20);
this->txtSide2->TabIndex = 1;
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(136, 26);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(68, 13);
this->label1->TabIndex = 2;
this->label1->Text = L"Side X Side";
//
// pctResult
//
this->pctResult->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;
this->pctResult->Location = System::Drawing::Point(316, 12);
this->pctResult->Name = L"pctResult";
this->pctResult->Size = System::Drawing::Size(440, 242);
this->pctResult->TabIndex = 3;
this->pctResult->TabStop = false;
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(12, 70);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(40, 13);
this->label2->TabIndex = 4;
this->label2->Text = L"Side1 :";
//
// label3
//
this->label3->AutoSize = true;
this->label3->Location = System::Drawing::Point(12, 112);
this->label3->Name = L"label3";
this->label3->Size = System::Drawing::Size(43, 13);
this->label3->TabIndex = 5;
this->label3->Text = L"Side2 :";
//
// txtSide1
//
this->txtSide1->Location = System::Drawing::Point(61, 67);
this->txtSide1->Name = L"txtSide1";
this->txtSide1->Size = System::Drawing::Size(238, 20);
this->txtSide1->TabIndex = 6;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(768, 273);
this->Controls->Add(this->txtSide1);
this->Controls->Add(this->label3);
this->Controls->Add(this->label2);
this->Controls->Add(this->pctResult);
this->Controls->Add(this->label1);
this->Controls->Add(this->txtSide2);
this->Controls->Add(this->BtnResult);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
(cli::safe_cast
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//Calculation Square
double SquareSide1;
double SquareSide2;
Graphics^SquareGraphics;
Pen^HPen;
double ResultCalSquare()
{
double ReSquare;
SquareSide1=System::Convert::ToDouble(txtSide1->Text);
SquareSide2=System::Convert::ToDouble(txtSide2->Text);
ReSquare=SquareSide1*SquareSide2;
return ReSquare;
}
void DrawSquare()
{
HPen=gcnew Pen(Color::Blue,1);
HPen->DashStyle=System::Drawing::Drawing2D::DashStyle::Dot;
SquareGraphics->DrawRectangle(HPen,10,10,SquareSide1,SquareSide2);
}
private: System::Void BtnResult_Click(System::Object^ sender, System::EventArgs^ e) {
ResultCalSquare();
this->Text="Side1 : "+SquareSide1+" X "+"Side2 : "+
SquareSide2+" = "+ResultCalSquare();
SquareGraphics=pctResult->CreateGraphics();
SquareGraphics->Clear(pctResult->BackColor);
DrawSquare();
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="Calculation Square";
this->BackColor=System::Drawing::Color::Aqua;
pctResult->BackColor=System::Drawing::Color::White;
}
};
}
Calculation Rectangle

#pragma once
namespace My10 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::TextBox^ txtRectangleWidth;
private: System::Windows::Forms::Button^ BtnResult;
protected:
protected:
private: System::Windows::Forms::TextBox^ txtRectangleLong;
private: System::Windows::Forms::Label^ lbl;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::PictureBox^ pctResult;
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->txtRectangleWidth = (gcnew System::Windows::Forms::TextBox());
this->BtnResult = (gcnew System::Windows::Forms::Button());
this->txtRectangleLong = (gcnew System::Windows::Forms::TextBox());
this->lbl = (gcnew System::Windows::Forms::Label());
this->label1 = (gcnew System::Windows::Forms::Label());
this->label2 = (gcnew System::Windows::Forms::Label());
this->pctResult = (gcnew System::Windows::Forms::PictureBox());
(cli::safe_cast
this->SuspendLayout();
//
// txtRectangleWidth
//
this->txtRectangleWidth->Location = System::Drawing::Point(58, 59);
this->txtRectangleWidth->Name = L"txtRectangleWidth";
this->txtRectangleWidth->Size = System::Drawing::Size(202, 20);
this->txtRectangleWidth->TabIndex = 0;
//
// BtnResult
//
this->BtnResult->Location = System::Drawing::Point(58, 152);
this->BtnResult->Name = L"BtnResult";
this->BtnResult->Size = System::Drawing::Size(202, 86);
this->BtnResult->TabIndex = 1;
this->BtnResult->Text = L"Show Result";
this->BtnResult->UseVisualStyleBackColor = true;
this->BtnResult->Click += gcnew System::EventHandler(this, &Form1::BtnResult_Click);
//
// txtRectangleLong
//
this->txtRectangleLong->Location = System::Drawing::Point(58, 106);
this->txtRectangleLong->Name = L"txtRectangleLong";
this->txtRectangleLong->Size = System::Drawing::Size(202, 20);
this->txtRectangleLong->TabIndex = 2;
//
// lbl
//
this->lbl->AutoSize = true;
this->lbl->Location = System::Drawing::Point(103, 20);
this->lbl->Name = L"lbl";
this->lbl->Size = System::Drawing::Size(90, 13);
this->lbl->TabIndex = 3;
this->lbl->Text = L": Width X Long";
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(12, 59);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(44, 13);
this->label1->TabIndex = 4;
this->label1->Text = L"Width : ";
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(12, 109);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(40, 13);
this->label2->TabIndex = 5;
this->label2->Text = L"Long : ";
//
// pctResult
//
this->pctResult->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;
this->pctResult->Location = System::Drawing::Point(273, 8);
this->pctResult->Name = L"pctResult";
this->pctResult->Size = System::Drawing::Size(420, 242);
this->pctResult->TabIndex = 6;
this->pctResult->TabStop = false;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(705, 263);
this->Controls->Add(this->pctResult);
this->Controls->Add(this->label2);
this->Controls->Add(this->label1);
this->Controls->Add(this->lbl);
this->Controls->Add(this->txtRectangleLong);
this->Controls->Add(this->BtnResult);
this->Controls->Add(this->txtRectangleWidth);
this->Name = L"Form1";
this->Text = L"Calculation Rectangle";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
(cli::safe_cast
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//Calculation a Rectangle
// Width X Long
double RectangleWidth;
double RectangleLong;
double CalculationRectangle()
{
double RectangleResult;
RectangleWidth=System::Convert::ToDouble(txtRectangleWidth->Text);
RectangleLong=System::Convert::ToDouble(txtRectangleLong->Text);
//Width X Long
RectangleResult=RectangleWidth*RectangleLong;
// Return Value
return RectangleResult;
}
void DrawCalRectangle(Graphics^RectangleGraphics,int RectangleX,
int RectangleY,int RectangleWidth,int RectangleHeight)
{
Pen^HPen;
HPen=gcnew Pen(Color::Black,1);
HPen->DashStyle=System::Drawing::Drawing2D::DashStyle::Dot;
RectangleGraphics->DrawRectangle(HPen,RectangleX,
RectangleY,RectangleWidth,RectangleHeight);
}
private: System::Void BtnResult_Click(System::Object^ sender, System::EventArgs^ e) {
double ReCalRectangle;
ReCalRectangle=CalculationRectangle();
this->Text="Width = "+RectangleWidth+
" Long = " +RectangleLong+ " = "+
ReCalRectangle;
Graphics^RecGraphics;
RecGraphics=pctResult->CreateGraphics();
RecGraphics->Clear(pctResult->BackColor);
DrawCalRectangle(RecGraphics,10,
10,RectangleWidth,RectangleLong);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
pctResult->BackColor=System::Drawing::Color::White;
this->BackColor=System::Drawing::Color::Yellow;
this->Text="Calculation Rectangle";
this->MaximizeBox=false;
}
};
}
Using Operator +

#pragma once
namespace My9 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ lblResult;
protected:
private: System::Windows::Forms::Button^ BtnResult;
private: System::Windows::Forms::Label^ lblNum2;
private: System::Windows::Forms::Label^ lblNum1;
private: System::Windows::Forms::Label^ lblOper;
private: System::Windows::Forms::Label^ label1;
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->lblResult = (gcnew System::Windows::Forms::Label());
this->BtnResult = (gcnew System::Windows::Forms::Button());
this->lblNum2 = (gcnew System::Windows::Forms::Label());
this->lblNum1 = (gcnew System::Windows::Forms::Label());
this->lblOper = (gcnew System::Windows::Forms::Label());
this->label1 = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// lblResult
//
this->lblResult->AutoSize = true;
this->lblResult->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, static_cast
System::Drawing::GraphicsUnit::Point, static_cast
this->lblResult->ForeColor = System::Drawing::Color::FromArgb(static_cast
static_cast
this->lblResult->Location = System::Drawing::Point(104, 128);
this->lblResult->Name = L"lblResult";
this->lblResult->Size = System::Drawing::Size(70, 22);
this->lblResult->TabIndex = 2;
this->lblResult->Text = L"............";
//
// BtnResult
//
this->BtnResult->Location = System::Drawing::Point(28, 176);
this->BtnResult->Name = L"BtnResult";
this->BtnResult->Size = System::Drawing::Size(252, 32);
this->BtnResult->TabIndex = 5;
this->BtnResult->Text = L"Show Result";
this->BtnResult->UseVisualStyleBackColor = true;
this->BtnResult->Click += gcnew System::EventHandler(this, &Form1::BtnResult_Click);
//
// lblNum2
//
this->lblNum2->AutoSize = true;
this->lblNum2->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, static_cast
System::Drawing::GraphicsUnit::Point, static_cast
this->lblNum2->ForeColor = System::Drawing::Color::Blue;
this->lblNum2->Location = System::Drawing::Point(115, 68);
this->lblNum2->Name = L"lblNum2";
this->lblNum2->Size = System::Drawing::Size(59, 22);
this->lblNum2->TabIndex = 6;
this->lblNum2->Text = L"label3";
//
// lblNum1
//
this->lblNum1->AutoSize = true;
this->lblNum1->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast
this->lblNum1->ForeColor = System::Drawing::Color::Yellow;
this->lblNum1->Location = System::Drawing::Point(115, 19);
this->lblNum1->Name = L"lblNum1";
this->lblNum1->Size = System::Drawing::Size(59, 22);
this->lblNum1->TabIndex = 7;
this->lblNum1->Text = L"label3";
//
// lblOper
//
this->lblOper->AutoSize = true;
this->lblOper->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast
this->lblOper->Location = System::Drawing::Point(180, 47);
this->lblOper->Name = L"lblOper";
this->lblOper->Size = System::Drawing::Size(21, 22);
this->lblOper->TabIndex = 8;
this->lblOper->Text = L"+";
//
// label1
//
this->label1->AutoSize = true;
this->label1->Font = (gcnew System::Drawing::Font(L"Times New Roman", 14.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast
this->label1->ForeColor = System::Drawing::Color::Black;
this->label1->Location = System::Drawing::Point(133, 90);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(21, 22);
this->label1->TabIndex = 9;
this->label1->Text = L"=";
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 211);
this->Controls->Add(this->label1);
this->Controls->Add(this->lblOper);
this->Controls->Add(this->lblNum1);
this->Controls->Add(this->lblNum2);
this->Controls->Add(this->BtnResult);
this->Controls->Add(this->lblResult);
this->ForeColor = System::Drawing::Color::Black;
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
int cNum1;
int cNum2;
int cResult;
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
cNum1=935800;
cNum2=108564;
lblNum1->Text=cNum1.ToString();
lblNum2->Text=cNum2.ToString();
this->BackColor=Color::Pink;
this->FormBorderStyle=Windows::Forms::FormBorderStyle::FixedToolWindow;
}
private: System::Void BtnResult_Click(System::Object^ sender, System::EventArgs^ e) {
cResult=cNum1+cNum2;
lblResult->Text=cResult.ToString();
}
};
}
Array

#pragma once
namespace My8 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::ListBox^ lstArray;
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->lstArray = (gcnew System::Windows::Forms::ListBox());
this->SuspendLayout();
//
// lstArray
//
this->lstArray->FormattingEnabled = true;
this->lstArray->Location = System::Drawing::Point(12, 21);
this->lstArray->Name = L"lstArray";
this->lstArray->Size = System::Drawing::Size(218, 225);
this->lstArray->TabIndex = 0;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(258, 258);
this->Controls->Add(this->lstArray);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Array
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
int a[]={5,10,15,20,25,30,35,40,45,50,
55,60,65,70,75,80,85,90,95,100,105,110};
int i;
for(i=0;i<=21;i++) { lstArray->Items->Add("Array : " +a[i].ToString());
}
this->BackColor=Color::Red;
lstArray->BackColor=Color::Yellow;
lstArray->ForeColor=Color::Blue;
this->FormBorderStyle=Windows::Forms::FormBorderStyle::FixedToolWindow;
this->Text="Using Array";
}
};
}
DrawArc

#pragma once
namespace My7 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::PictureBox^ pct;
private: System::Windows::Forms::Button^ BtnDrawArc;
protected:
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->pct = (gcnew System::Windows::Forms::PictureBox());
this->BtnDrawArc = (gcnew System::Windows::Forms::Button());
(cli::safe_cast
this->SuspendLayout();
//
// pct
//
this->pct->Location = System::Drawing::Point(15, 18);
this->pct->Name = L"pct";
this->pct->Size = System::Drawing::Size(281, 264);
this->pct->TabIndex = 0;
this->pct->TabStop = false;
//
// BtnDrawArc
//
this->BtnDrawArc->Location = System::Drawing::Point(127, 288);
this->BtnDrawArc->Name = L"BtnDrawArc";
this->BtnDrawArc->Size = System::Drawing::Size(74, 32);
this->BtnDrawArc->TabIndex = 1;
this->BtnDrawArc->Text = L"DrawArc";
this->BtnDrawArc->UseVisualStyleBackColor = true;
this->BtnDrawArc->Click += gcnew System::EventHandler(this, &Form1::BtnDrawArc_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(312, 326);
this->Controls->Add(this->BtnDrawArc);
this->Controls->Add(this->pct);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
(cli::safe_cast
this->ResumeLayout(false);
}
#pragma endregion
//DrawArc
private: System::Void BtnDrawArc_Click(System::Object^ sender, System::EventArgs^ e) {
Graphics^TestGraphics;
Pen^HPen;
TestGraphics=pct->CreateGraphics();
HPen=gcnew Pen(Color::Yellow,2);
TestGraphics->DrawArc(HPen,10,10,200,200,50,160);
TestGraphics->DrawArc(HPen,50,10,150,150,100,250);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
pct->BorderStyle=Windows::Forms::BorderStyle::Fixed3D;
pct->BackColor=Color::Black;
this->BackColor=Color::Green;
this->Text="DrawArc";
}
};
}
Using Progress Bar

#pragma once
namespace My6 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::ProgressBar^ pgb1;
protected:
private: System::Windows::Forms::Button^ BtnStart;
private: System::Windows::Forms::Label^ lblPercent;
private: System::Windows::Forms::ProgressBar^ pgb2;
private: System::Windows::Forms::Timer^ t;
private: System::ComponentModel::IContainer^ components;
private:
///
/// Required designer variable.
///
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
this->pgb1 = (gcnew System::Windows::Forms::ProgressBar());
this->BtnStart = (gcnew System::Windows::Forms::Button());
this->lblPercent = (gcnew System::Windows::Forms::Label());
this->pgb2 = (gcnew System::Windows::Forms::ProgressBar());
this->t = (gcnew System::Windows::Forms::Timer(this->components));
this->SuspendLayout();
//
// pgb1
//
this->pgb1->Location = System::Drawing::Point(12, 48);
this->pgb1->Name = L"pgb1";
this->pgb1->Size = System::Drawing::Size(502, 28);
this->pgb1->TabIndex = 0;
//
// BtnStart
//
this->BtnStart->Location = System::Drawing::Point(205, 127);
this->BtnStart->Name = L"BtnStart";
this->BtnStart->Size = System::Drawing::Size(127, 40);
this->BtnStart->TabIndex = 1;
this->BtnStart->Text = L"Start";
this->BtnStart->UseVisualStyleBackColor = true;
this->BtnStart->Click += gcnew System::EventHandler(this, &Form1::BtnStart_Click);
//
// lblPercent
//
this->lblPercent->AutoSize = true;
this->lblPercent->Location = System::Drawing::Point(235, 22);
this->lblPercent->Name = L"lblPercent";
this->lblPercent->Size = System::Drawing::Size(21, 13);
this->lblPercent->TabIndex = 2;
this->lblPercent->Text = L"0%";
//
// pgb2
//
this->pgb2->Location = System::Drawing::Point(12, 82);
this->pgb2->Name = L"pgb2";
this->pgb2->Size = System::Drawing::Size(502, 28);
this->pgb2->TabIndex = 3;
//
// t
//
this->t->Interval = 1;
this->t->Tick += gcnew System::EventHandler(this, &Form1::t_Tick);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(538, 170);
this->Controls->Add(this->pgb2);
this->Controls->Add(this->lblPercent);
this->Controls->Add(this->BtnStart);
this->Controls->Add(this->pgb1);
this->Name = L"Form1";
this->Text = L"Form1";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
//Using Progress Bar
private: System::Void BtnStart_Click(System::Object^ sender, System::EventArgs^ e) {
pgb1->Value=0;
pgb2->Value=0;
t->Enabled=true;
BtnStart->Enabled=false;
}
private: System::Void t_Tick(System::Object^ sender, System::EventArgs^ e) {
pgb1->Value=pgb1->Value+1;
if(pgb1->Value==pgb1->Maximum)
{
pgb1->Value=pgb1->Minimum;
pgb2->Value=pgb2->Value+1;
lblPercent->Text=pgb2->Value.ToString()+"%";
if(pgb2->Value==pgb2->Maximum)
{
t->Enabled=false;
BtnStart->Enabled=true;
}
}
}
};
}
Create Function

#pragma once
namespace My5 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Create Function
int Max(String^Str)
{
int Len;
Len=Str->Length;
return Len;
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text=Max("String").ToString();
this->Width=200;
this->Height=50;
this->FormBorderStyle=Windows::Forms::FormBorderStyle::FixedToolWindow;
this->BackColor=Color::Violet;
}
};
}
Create Function 1

#pragma once
namespace My4 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Create Function 1
float Max(int NumValue)
{
float ReValue;
ReValue=NumValue/(75*36);
return ReValue;
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
float Sum;
Sum=Max(66758490);
this->Text=Sum.ToString();
this->BackColor=Color::PaleGreen;
this->FormBorderStyle=Windows::Forms::FormBorderStyle::FixedToolWindow;
}
};
}
Using MessageBox

#pragma once
namespace My3 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//Using MessageBox
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
MessageBox::Show("Using MessageBox","MessageBox",MessageBoxButtons::OK,
MessageBoxIcon::Information);
}
};
}
MouseMove GetCurrent X , GetCurrent Y

#pragma once
namespace My2 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::Form1_MouseMove);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//MouseMove GetCurrent X , GetCurrent Y
private: System::Void Form1_MouseMove(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
this->Text="Mouse X : " + e->X.ToString()+
" Mouse Y : " + e->Y.ToString();
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="MouseMove GetCurrent X , GetCurrent Y";
this->FormBorderStyle=Windows::Forms::FormBorderStyle::FixedToolWindow;
this->Width=300;
this->Height=300;
this->BackColor=Color::Red;
}
};
}
namespace My2 {
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 for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
protected:
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->MouseMove += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::Form1_MouseMove);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//MouseMove GetCurrent X , GetCurrent Y
private: System::Void Form1_MouseMove(System::Object^ sender, System::Windows::Forms::MouseEventArgs^ e) {
this->Text="Mouse X : " + e->X.ToString()+
" Mouse Y : " + e->Y.ToString();
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="MouseMove GetCurrent X , GetCurrent Y";
this->FormBorderStyle=Windows::Forms::FormBorderStyle::FixedToolWindow;
this->Width=300;
this->Height=300;
this->BackColor=Color::Red;
}
};
}
DrawLine

#pragma once
namespace My1 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Drawing::Drawing2D;
///
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::Form1_Paint);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//DrawLine
private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
Graphics^TestGraphics;
Pen^HPen;
TestGraphics=this->CreateGraphics();
HPen=gcnew Pen(Color::White,2);
TestGraphics->DrawLine(HPen,0,0,this->Width+20,this->Height);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="DrawLine";
this->Width=500;
this->Height=500;
this->FormBorderStyle=Windows::Forms::FormBorderStyle::FixedToolWindow;
this->BackColor=Color::Black;
}
};
}
namespace My1 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Drawing::Drawing2D;
///
/// Summary for Form1
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
///
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
///
/// Clean up any resources being used.
///
~Form1()
{
if (components)
{
delete components;
}
}
private:
///
/// Required designer variable.
///
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
void InitializeComponent(void)
{
this->SuspendLayout();
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Name = L"Form1";
this->Text = L"Form1";
this->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &Form1::Form1_Paint);
this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
this->ResumeLayout(false);
}
#pragma endregion
//DrawLine
private: System::Void Form1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) {
Graphics^TestGraphics;
Pen^HPen;
TestGraphics=this->CreateGraphics();
HPen=gcnew Pen(Color::White,2);
TestGraphics->DrawLine(HPen,0,0,this->Width+20,this->Height);
}
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
this->Text="DrawLine";
this->Width=500;
this->Height=500;
this->FormBorderStyle=Windows::Forms::FormBorderStyle::FixedToolWindow;
this->BackColor=Color::Black;
}
};
}
The Edit Buffer
Taken collectively, the field data members of a recordset serve as an edit buffer that contains one record — the current record. Update operations use this buffer to operate on the current record.
When you add a record, the edit buffer is used to build a new record. When you finish adding the record, the record that was previously current becomes current again.
When you update (edit) a record, the edit buffer is used to set the field data members of the recordset to new values. When you finish updating, the updated record is still current.
When you call AddNew or Edit, the current record is stored so it can be restored later as needed. When you call Delete, the current record is not stored but is marked as deleted and you must scroll to another record.
Note The edit buffer plays no role in record deletion. When you delete the current record, the record is marked as deleted, and the recordset is "not on a record" until you scroll to a different record.
Dynasets and SnapshotsDynasets refresh a record's contents as you scroll to the record. Snapshots are static representations of the records, so a record's contents are not refreshed unless you call Requery. To use all the functionality of dynasets, you must be working with an ODBC driver that conforms to the correct level of ODBC API support. For more information, see ODBC and Dynaset.
Snapshot
A snapshot is a recordset that reflects a static view of the data as it existed at the time the snapshot was created. When you open the snapshot and move to all the records, the set of records it contains and their values do not change until you rebuild the snapshot by calling Requery.
Note This topic applies to the MFC ODBC classes. If you are using the MFC DAO classes instead of the MFC ODBC classes, see CDaoRecordset::Open for a description of snapshot-type recordsets.
You can create updateable or read-only snapshots with the database classes. Unlike a dynaset, an updateable snapshot does not reflect changes to record values made by other users, but it does reflect updates and deletions made by your program. Records added to a snapshot do not become visible to the snapshot until you call Requery.
Tip A snapshot is an ODBC static cursor. Static cursors do not actually get a row of data until you scroll to that record. To ensure that all records are immediately retrieved, you can scroll to the end of your recordset and then scroll to the first record you want to see. Note, however, that scrolling to the end entails extra overhead and can lower performance.
Snapshots are most valuable when you need the data to remain fixed during your operations, as when you are generating a report or performing calculations. Even so, the data source can diverge considerably from your snapshot, so you might want to rebuild it from time to time.
Snapshot support is based on the ODBC Cursor Library, which provides static cursors and positioned updates (needed for updateability) for any Level 1 driver. The cursor library DLL must be loaded in memory for this support. When you construct a CDatabase object and call its OpenEx member function, you must specify the CDatabase::useCursorLib option of the dwOptions parameter. If you call the Open member function, the cursor library is loaded by default. If you are using dynasets instead of snapshots, you do not want to cause the cursor library to be loaded.
Snapshots are available only if the ODBC Cursor Library was loaded when the CDatabase object was constructed or the ODBC driver you are using supports static cursors.
Note For some ODBC drivers, snapshots (static cursors) might not be updateable. Check your driver documentation for cursor types supported and the concurrency types they support. To guarantee updateable snapshots, make sure you load the cursor library into memory when you create a CDatabase object. For more information, see ODBC: The ODBC Cursor Library. Note If you want to use both snapshots and dynasets, you must base them on two different CDatabase objects (two different connections).
For more information about the properties snapshots share with all recordsets, see Recordset (ODBC). For more information about ODBC and snapshots, including the ODBC Cursor Library, see ODBC.
When you add a record, the edit buffer is used to build a new record. When you finish adding the record, the record that was previously current becomes current again.
When you update (edit) a record, the edit buffer is used to set the field data members of the recordset to new values. When you finish updating, the updated record is still current.
When you call AddNew or Edit, the current record is stored so it can be restored later as needed. When you call Delete, the current record is not stored but is marked as deleted and you must scroll to another record.
Note The edit buffer plays no role in record deletion. When you delete the current record, the record is marked as deleted, and the recordset is "not on a record" until you scroll to a different record.
Dynasets and SnapshotsDynasets refresh a record's contents as you scroll to the record. Snapshots are static representations of the records, so a record's contents are not refreshed unless you call Requery. To use all the functionality of dynasets, you must be working with an ODBC driver that conforms to the correct level of ODBC API support. For more information, see ODBC and Dynaset.
Snapshot
A snapshot is a recordset that reflects a static view of the data as it existed at the time the snapshot was created. When you open the snapshot and move to all the records, the set of records it contains and their values do not change until you rebuild the snapshot by calling Requery.
Note This topic applies to the MFC ODBC classes. If you are using the MFC DAO classes instead of the MFC ODBC classes, see CDaoRecordset::Open for a description of snapshot-type recordsets.
You can create updateable or read-only snapshots with the database classes. Unlike a dynaset, an updateable snapshot does not reflect changes to record values made by other users, but it does reflect updates and deletions made by your program. Records added to a snapshot do not become visible to the snapshot until you call Requery.
Tip A snapshot is an ODBC static cursor. Static cursors do not actually get a row of data until you scroll to that record. To ensure that all records are immediately retrieved, you can scroll to the end of your recordset and then scroll to the first record you want to see. Note, however, that scrolling to the end entails extra overhead and can lower performance.
Snapshots are most valuable when you need the data to remain fixed during your operations, as when you are generating a report or performing calculations. Even so, the data source can diverge considerably from your snapshot, so you might want to rebuild it from time to time.
Snapshot support is based on the ODBC Cursor Library, which provides static cursors and positioned updates (needed for updateability) for any Level 1 driver. The cursor library DLL must be loaded in memory for this support. When you construct a CDatabase object and call its OpenEx member function, you must specify the CDatabase::useCursorLib option of the dwOptions parameter. If you call the Open member function, the cursor library is loaded by default. If you are using dynasets instead of snapshots, you do not want to cause the cursor library to be loaded.
Snapshots are available only if the ODBC Cursor Library was loaded when the CDatabase object was constructed or the ODBC driver you are using supports static cursors.
Note For some ODBC drivers, snapshots (static cursors) might not be updateable. Check your driver documentation for cursor types supported and the concurrency types they support. To guarantee updateable snapshots, make sure you load the cursor library into memory when you create a CDatabase object. For more information, see ODBC: The ODBC Cursor Library. Note If you want to use both snapshots and dynasets, you must base them on two different CDatabase objects (two different connections).
For more information about the properties snapshots share with all recordsets, see Recordset (ODBC). For more information about ODBC and snapshots, including the ODBC Cursor Library, see ODBC.
Transaction: How Transactions Affect Updates (ODBC)
Updates to the data source are managed during transactions through the use of an edit buffer (the same method used outside of transactions). The field data members of a recordset collectively serve as an edit buffer that contains the current record, which the recordset backs up temporarily during an AddNew or Edit. During a Delete operation, the current record is not backed up within a transaction. For more information about the edit buffer and how updates store the current record, see Recordset: How Recordsets Update Records (ODBC).
Note If you have implemented bulk row fetching, you cannot call AddNew, Edit, or Delete. You must instead write your own functions to perform updates to the data source. For more information about bulk row fetching, see Recordset: Fetching Records in Bulk (ODBC).
During transactions, AddNew, Edit, and Delete operations can be committed or rolled back. The effects of CommitTrans and Rollback might cause the current record to not be restored to the edit buffer. To make sure that the current record is properly restored, it is important to understand how the CommitTrans and Rollback member functions of CDatabase work with the update functions of CRecordset.
The Edit Buffer
Recordset: How Recordsets Update Records (ODBC)
This topic applies to the MFC ODBC classes.
Besides their ability to select records from a data source, recordsets can (optionally) update or delete the selected records or add new records. Three factors determine a recordset's updateability: whether the connected data source is updateable, the options you specify when you create a recordset object, and the SQL that is created.
Note The SQL on which your CRecordset object is based can affect your recordset's updateability. For example, if your SQL contains a join or a GROUP BY clause, MFC sets the updateability to FALSE.Note This topic applies to objects derived from CRecordset in which bulk row fetching has not been implemented. If you are using bulk row fetching, see Recordset: Fetching Records in Bulk (ODBC).
This topic explains:
Your role in recordset updating and what the framework does for you.
The recordset as an edit buffer and the differences between dynasets and snapshots.
Recordset: How AddNew, Edit, and Delete Work (ODBC) describes the actions of these functions from the point of view of the recordset.
Recordset: More About Updates (ODBC) completes the recordset update story by explaining how transactions affect updates, how closing a recordset or scrolling affects updates in progress, and how your updates interact with the updates of other users.
Note If you have implemented bulk row fetching, you cannot call AddNew, Edit, or Delete. You must instead write your own functions to perform updates to the data source. For more information about bulk row fetching, see Recordset: Fetching Records in Bulk (ODBC).
During transactions, AddNew, Edit, and Delete operations can be committed or rolled back. The effects of CommitTrans and Rollback might cause the current record to not be restored to the edit buffer. To make sure that the current record is properly restored, it is important to understand how the CommitTrans and Rollback member functions of CDatabase work with the update functions of CRecordset.
The Edit Buffer
Recordset: How Recordsets Update Records (ODBC)
This topic applies to the MFC ODBC classes.
Besides their ability to select records from a data source, recordsets can (optionally) update or delete the selected records or add new records. Three factors determine a recordset's updateability: whether the connected data source is updateable, the options you specify when you create a recordset object, and the SQL that is created.
Note The SQL on which your CRecordset object is based can affect your recordset's updateability. For example, if your SQL contains a join or a GROUP BY clause, MFC sets the updateability to FALSE.Note This topic applies to objects derived from CRecordset in which bulk row fetching has not been implemented. If you are using bulk row fetching, see Recordset: Fetching Records in Bulk (ODBC).
This topic explains:
Your role in recordset updating and what the framework does for you.
The recordset as an edit buffer and the differences between dynasets and snapshots.
Recordset: How AddNew, Edit, and Delete Work (ODBC) describes the actions of these functions from the point of view of the recordset.
Recordset: More About Updates (ODBC) completes the recordset update story by explaining how transactions affect updates, how closing a recordset or scrolling affects updates in progress, and how your updates interact with the updates of other users.
Transaction: Performing a Transaction in a Recordset (ODBC)
This topic explains how to perform a transaction in a recordset.
Note Only one level of transactions is supported; you cannot nest transactions.To perform a transaction in a recordsetCall the CDatabase object's BeginTrans member function.
If you have not implemented bulk row fetching, call the AddNew/Update, Edit/Update, and Delete member functions of one or more recordset objects of the same database as many times as needed. For more information, see Recordset: Adding, Updating, and Deleting Records (ODBC). If you have implemented bulk row fetching, you must write your own functions to update the data source.
Finally, call the CDatabase object's CommitTrans member function. If an error occurs in one of the updates or you decide to cancel the changes, call its Rollback member function.
The following example uses two recordsets to delete a student's enrollment from a school registration database, removing the student from all classes in which the student is enrolled. Because the Delete calls in both recordsets must succeed, a transaction is required. The example assumes the existence of m_dbStudentReg, a member variable of type CDatabase already connected to the data source, and the recordset classes CEnrollmentSet and CStudentSet. The strStudentID variable contains a value obtained from the user.BOOL CEnrollDoc::RemoveStudent( CString strStudentID ){// remove student from all the classes// the student is enrolled in
if ( !m_dbStudentReg.BeginTrans( ) )return FALSE;
CEnrollmentSet rsEnrollmentSet(&m_dbStudentReg);rsEnrollmentSet.m_strFilter = "StudentID = " + strStudentID;
if ( !rsEnrollmentSet.Open(CRecordset::dynaset) )return FALSE;
CStudentSet rsStudentSet(&m_dbStudentReg);rsStudentSet.m_strFilter = "StudentID = " + strStudentID;
if ( !rsStudentSet.Open(CRecordset::dynaset) )return FALSE;
TRY{while ( !rsEnrollmentSet.IsEOF( ) ){rsEnrollmentSet.Delete( );rsEnrollmentSet.MoveNext( );}
// delete the student recordrsStudentSet.Delete( );
m_dbStudentReg.CommitTrans( );}
CATCH_ALL(e){m_dbStudentReg.Rollback( );return FALSE;}END_CATCH_ALL
rsEnrollmentSet.Close( );rsStudentSet.Close( );
return TRUE;
}Note Calling BeginTrans again without calling CommitTrans or Rollback is an error.
Note Only one level of transactions is supported; you cannot nest transactions.To perform a transaction in a recordsetCall the CDatabase object's BeginTrans member function.
If you have not implemented bulk row fetching, call the AddNew/Update, Edit/Update, and Delete member functions of one or more recordset objects of the same database as many times as needed. For more information, see Recordset: Adding, Updating, and Deleting Records (ODBC). If you have implemented bulk row fetching, you must write your own functions to update the data source.
Finally, call the CDatabase object's CommitTrans member function. If an error occurs in one of the updates or you decide to cancel the changes, call its Rollback member function.
The following example uses two recordsets to delete a student's enrollment from a school registration database, removing the student from all classes in which the student is enrolled. Because the Delete calls in both recordsets must succeed, a transaction is required. The example assumes the existence of m_dbStudentReg, a member variable of type CDatabase already connected to the data source, and the recordset classes CEnrollmentSet and CStudentSet. The strStudentID variable contains a value obtained from the user.BOOL CEnrollDoc::RemoveStudent( CString strStudentID ){// remove student from all the classes// the student is enrolled in
if ( !m_dbStudentReg.BeginTrans( ) )return FALSE;
CEnrollmentSet rsEnrollmentSet(&m_dbStudentReg);rsEnrollmentSet.m_strFilter = "StudentID = " + strStudentID;
if ( !rsEnrollmentSet.Open(CRecordset::dynaset) )return FALSE;
CStudentSet rsStudentSet(&m_dbStudentReg);rsStudentSet.m_strFilter = "StudentID = " + strStudentID;
if ( !rsStudentSet.Open(CRecordset::dynaset) )return FALSE;
TRY{while ( !rsEnrollmentSet.IsEOF( ) ){rsEnrollmentSet.Delete( );rsEnrollmentSet.MoveNext( );}
// delete the student recordrsStudentSet.Delete( );
m_dbStudentReg.CommitTrans( );}
CATCH_ALL(e){m_dbStudentReg.Rollback( );return FALSE;}END_CATCH_ALL
rsEnrollmentSet.Close( );rsStudentSet.Close( );
return TRUE;
}Note Calling BeginTrans again without calling CommitTrans or Rollback is an error.
How to: Marshal a SAFEARRAY for ADO.NET
Demonstrates how to add a native SAFEARRAY to a database and how to marshal a managed array from a database to a native SAFEARRAY.
ExampleIn this example, the class DatabaseClass is created to interact with an ADO.NET DataTable object. Note that this class is a native C++ class (as compared to a ref class or value class). This is necessary because we want to use this class from native code, and you cannot use managed types in native code. This class will be compiled to target the CLR, as is indicated by the #pragma managed directive preceding the class declaration. For more information on this directive, see managed, unmanaged.
Note the private member of the DatabaseClass class: gcroot table. Since native types cannot contain managed types, the gcroot keyword is necessary. For more information on gcroot, see How to: Declare Handles in Native Types.
The rest of the code in this example is native C++ code, as is indicated by the #pragma unmanaged directive preceding main. In this example, we are creating a new instance of DatabaseClass and calling its methods to create a table and populate some rows in the table. Note that native SAFEARRAY types are being passed as values for the database column ArrayIntsCol. Inside DatabaseClass, these SAFEARRAY types are marshaled to managed objects using the marshaling functionality found in the System.Runtime.InteropServices namespace. Specifically, the method Copy is used to marshal a SAFEARRAY to a managed array of integers, and the method Copy is used to marshal a managed array of integers to a SAFEARRAY.
// adonet_marshal_safearray.cpp// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll#include#include #include using namespace std;
#usingusing namespace System;using namespace System::Data;using namespace System::Runtime::InteropServices;
#define MAXCOLS 100
#pragma managedclass DatabaseClass{public:DatabaseClass() : table(nullptr) { }
void AddRow(SAFEARRAY *arrayIntsColValue){// Add a row to the table.DataRow ^row = table->NewRow();int len = arrayIntsColValue->rgsabound[0].cElements;array ^arr = gcnew array(len);
int *pData;SafeArrayAccessData(arrayIntsColValue, (void **)&pData);Marshal::Copy(IntPtr(pData), arr, 0, len);SafeArrayUnaccessData(arrayIntsColValue);
row["ArrayIntsCol"] = arr;table->Rows->Add(row);}
void CreateAndPopulateTable(){// Create a simple DataTable.table = gcnew DataTable("SampleTable");
// Add a column of type String to the table.DataColumn ^column1 = gcnew DataColumn("ArrayIntsCol",Type::GetType("System.Int32[]"));table->Columns->Add(column1);}
int GetValuesForColumn(wchar_t *dataColumn, SAFEARRAY **values,int valuesLength){// Marshal the name of the column to a managed// String.String ^columnStr = Marshal::PtrToStringUni((IntPtr)dataColumn);
// Get all rows in the table.array ^rows = table->Select();int len = rows->Length;len = (len > valuesLength) ? valuesLength : len;for (int i = 0; i <> ^)rows[i][columnStr], 0,IntPtr(pData), 10);SafeArrayUnaccessData(values[i]);}
return len;}
private:// Using gcroot, you can use a managed type in// a native class.gcroot table;};
#pragma unmanagedint main(){// Create a table and add a few rows to it.DatabaseClass *db = new DatabaseClass();db->CreateAndPopulateTable();
// Create a standard array.int originalArray[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Create a SAFEARRAY.SAFEARRAY *psa;psa = SafeArrayCreateVector(VT_I4, 0, 10);
// Copy the data from the original array to the SAFEARRAY.int *pData;HRESULT hr = SafeArrayAccessData(psa, (void **)&pData);memcpy(pData, &originalArray, 40);SafeArrayUnaccessData(psa);db->AddRow(psa);
// Now retrieve the rows and display their contents.SAFEARRAY *values[MAXCOLS];int len = db->GetValuesForColumn(L"ArrayIntsCol", values, MAXCOLS);for (int i = 0; i < j =" 0;">
ExampleIn this example, the class DatabaseClass is created to interact with an ADO.NET DataTable object. Note that this class is a native C++ class (as compared to a ref class or value class). This is necessary because we want to use this class from native code, and you cannot use managed types in native code. This class will be compiled to target the CLR, as is indicated by the #pragma managed directive preceding the class declaration. For more information on this directive, see managed, unmanaged.
Note the private member of the DatabaseClass class: gcroot
The rest of the code in this example is native C++ code, as is indicated by the #pragma unmanaged directive preceding main. In this example, we are creating a new instance of DatabaseClass and calling its methods to create a table and populate some rows in the table. Note that native SAFEARRAY types are being passed as values for the database column ArrayIntsCol. Inside DatabaseClass, these SAFEARRAY types are marshaled to managed objects using the marshaling functionality found in the System.Runtime.InteropServices namespace. Specifically, the method Copy is used to marshal a SAFEARRAY to a managed array of integers, and the method Copy is used to marshal a managed array of integers to a SAFEARRAY.
// adonet_marshal_safearray.cpp// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll#include
#using
#define MAXCOLS 100
#pragma managedclass DatabaseClass{public:DatabaseClass() : table(nullptr) { }
void AddRow(SAFEARRAY *arrayIntsColValue){// Add a row to the table.DataRow ^row = table->NewRow();int len = arrayIntsColValue->rgsabound[0].cElements;array
int *pData;SafeArrayAccessData(arrayIntsColValue, (void **)&pData);Marshal::Copy(IntPtr(pData), arr, 0, len);SafeArrayUnaccessData(arrayIntsColValue);
row["ArrayIntsCol"] = arr;table->Rows->Add(row);}
void CreateAndPopulateTable(){// Create a simple DataTable.table = gcnew DataTable("SampleTable");
// Add a column of type String to the table.DataColumn ^column1 = gcnew DataColumn("ArrayIntsCol",Type::GetType("System.Int32[]"));table->Columns->Add(column1);}
int GetValuesForColumn(wchar_t *dataColumn, SAFEARRAY **values,int valuesLength){// Marshal the name of the column to a managed// String.String ^columnStr = Marshal::PtrToStringUni((IntPtr)dataColumn);
// Get all rows in the table.array
return len;}
private:// Using gcroot, you can use a managed type in// a native class.gcroot
#pragma unmanagedint main(){// Create a table and add a few rows to it.DatabaseClass *db = new DatabaseClass();db->CreateAndPopulateTable();
// Create a standard array.int originalArray[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Create a SAFEARRAY.SAFEARRAY *psa;psa = SafeArrayCreateVector(VT_I4, 0, 10);
// Copy the data from the original array to the SAFEARRAY.int *pData;HRESULT hr = SafeArrayAccessData(psa, (void **)&pData);memcpy(pData, &originalArray, 40);SafeArrayUnaccessData(psa);db->AddRow(psa);
// Now retrieve the rows and display their contents.SAFEARRAY *values[MAXCOLS];int len = db->GetValuesForColumn(L"ArrayIntsCol", values, MAXCOLS);for (int i = 0; i < j =" 0;">
How to: Marshal BSTR Strings for ADO.NET
Demonstrates how to add a COM string (BSTR) to a database and how to marshal a System.String from a database to a BSTR.
ExampleIn this example, the class DatabaseClass is created to interact with an ADO.NET DataTable object. Note that this class is a native C++ class (as compared to a ref class or value class). This is necessary because we want to use this class from native code, and you cannot use managed types in native code. This class will be compiled to target the CLR, as is indicated by the #pragma managed directive preceding the class declaration. For more information on this directive, see managed, unmanaged.
Note the private member of the DatabaseClass class: gcroot table. Since native types cannot contain managed types, the gcroot keyword is necessary. For more information on gcroot, see How to: Declare Handles in Native Types.
The rest of the code in this example is native C++ code, as is indicated by the #pragma unmanaged directive preceding main. In this example, we are creating a new instance of DatabaseClass and calling its methods to create a table and populate some rows in the table. Note that COM strings are being passed as values for the database column StringCol. Inside DatabaseClass, these strings are marshaled to managed strings using the marshaling functionality found in the System.Runtime.InteropServices namespace. Specifically, the method PtrToStringBSTR is used to marshal a BSTR to a String, and the method StringToBSTR is used to marshal a String to a BSTR.
Note The memory allocated by StringToBSTR must be deallocated by calling either FreeBSTR or SysFreeString.// adonet_marshal_string_bstr.cpp// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll#include#include #include using namespace std;
#usingusing namespace System;using namespace System::Data;using namespace System::Runtime::InteropServices;
#define MAXCOLS 100
#pragma managedclass DatabaseClass{public:DatabaseClass() : table(nullptr) { }
void AddRow(BSTR stringColValue){// Add a row to the table.DataRow ^row = table->NewRow();row["StringCol"] = Marshal::PtrToStringBSTR((IntPtr)stringColValue);table->Rows->Add(row);}
void CreateAndPopulateTable(){// Create a simple DataTable.table = gcnew DataTable("SampleTable");
// Add a column of type String to the table.DataColumn ^column1 = gcnew DataColumn("StringCol",Type::GetType("System.String"));table->Columns->Add(column1);}
int GetValuesForColumn(BSTR dataColumn, BSTR *values,int valuesLength){// Marshal the name of the column to a managed// String.String ^columnStr = Marshal::PtrToStringBSTR((IntPtr)dataColumn);
// Get all rows in the table.array ^rows = table->Select();int len = rows->Length;len = (len > valuesLength) ? valuesLength : len;for (int i = 0; i <> table;};
#pragma unmanagedint main(){// Create a table and add a few rows to it.DatabaseClass *db = new DatabaseClass();db->CreateAndPopulateTable();
BSTR str1 = SysAllocString(L"This is string 1.");db->AddRow(str1);
BSTR str2 = SysAllocString(L"This is string 2.");db->AddRow(str2);
// Now retrieve the rows and display their contents.BSTR values[MAXCOLS];BSTR str3 = SysAllocString(L"StringCol");int len = db->GetValuesForColumn(str3, values, MAXCOLS);for (int i = 0; i <>
ExampleIn this example, the class DatabaseClass is created to interact with an ADO.NET DataTable object. Note that this class is a native C++ class (as compared to a ref class or value class). This is necessary because we want to use this class from native code, and you cannot use managed types in native code. This class will be compiled to target the CLR, as is indicated by the #pragma managed directive preceding the class declaration. For more information on this directive, see managed, unmanaged.
Note the private member of the DatabaseClass class: gcroot
The rest of the code in this example is native C++ code, as is indicated by the #pragma unmanaged directive preceding main. In this example, we are creating a new instance of DatabaseClass and calling its methods to create a table and populate some rows in the table. Note that COM strings are being passed as values for the database column StringCol. Inside DatabaseClass, these strings are marshaled to managed strings using the marshaling functionality found in the System.Runtime.InteropServices namespace. Specifically, the method PtrToStringBSTR is used to marshal a BSTR to a String, and the method StringToBSTR is used to marshal a String to a BSTR.
Note The memory allocated by StringToBSTR must be deallocated by calling either FreeBSTR or SysFreeString.// adonet_marshal_string_bstr.cpp// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll#include
#using
#define MAXCOLS 100
#pragma managedclass DatabaseClass{public:DatabaseClass() : table(nullptr) { }
void AddRow(BSTR stringColValue){// Add a row to the table.DataRow ^row = table->NewRow();row["StringCol"] = Marshal::PtrToStringBSTR((IntPtr)stringColValue);table->Rows->Add(row);}
void CreateAndPopulateTable(){// Create a simple DataTable.table = gcnew DataTable("SampleTable");
// Add a column of type String to the table.DataColumn ^column1 = gcnew DataColumn("StringCol",Type::GetType("System.String"));table->Columns->Add(column1);}
int GetValuesForColumn(BSTR dataColumn, BSTR *values,int valuesLength){// Marshal the name of the column to a managed// String.String ^columnStr = Marshal::PtrToStringBSTR((IntPtr)dataColumn);
// Get all rows in the table.array
#pragma unmanagedint main(){// Create a table and add a few rows to it.DatabaseClass *db = new DatabaseClass();db->CreateAndPopulateTable();
BSTR str1 = SysAllocString(L"This is string 1.");db->AddRow(str1);
BSTR str2 = SysAllocString(L"This is string 2.");db->AddRow(str2);
// Now retrieve the rows and display their contents.BSTR values[MAXCOLS];BSTR str3 = SysAllocString(L"StringCol");int len = db->GetValuesForColumn(str3, values, MAXCOLS);for (int i = 0; i <>
How to: Marshal ANSI Strings for ADO.NET
Demonstrates how to add a native string (char *) to a database and how to marshal a System.String from a database to a native string.
ExampleIn this example, the class DatabaseClass is created to interact with an ADO.NET DataTable object. Note that this class is a native C++ class (as compared to a ref class or value class). This is necessary because we want to use this class from native code, and you cannot use managed types in native code. This class will be compiled to target the CLR, as is indicated by the #pragma managed directive preceding the class declaration. For more information on this directive, see managed, unmanaged.
Note the private member of the DatabaseClass class: gcroot table. Since native types cannot contain managed types, the gcroot keyword is necessary. For more information on gcroot, see How to: Declare Handles in Native Types.
The rest of the code in this example is native C++ code, as is indicated by the #pragma unmanaged directive preceding main. In this example, we are creating a new instance of DatabaseClass and calling its methods to create a table and populate some rows in the table. Note that native C++ strings are being passed as values for the database column StringCol. Inside DatabaseClass, these strings are marshaled to managed strings using the marshaling functionality found in the System.Runtime.InteropServices namespace. Specifically, the method PtrToStringAnsi is used to marshal a char * to a String, and the method StringToHGlobalAnsi is used to marshal a String to a char *.
Note The memory allocated by StringToHGlobalAnsi must be deallocated by calling either FreeHGlobal or GlobalFree.// adonet_marshal_string_native.cpp// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll#include#include #include using namespace std;
#usingusing namespace System;using namespace System::Data;using namespace System::Runtime::InteropServices;
#define MAXCOLS 100
#pragma managedclass DatabaseClass{public:DatabaseClass() : table(nullptr) { }
void AddRow(char *stringColValue){// Add a row to the table.DataRow ^row = table->NewRow();row["StringCol"] = Marshal::PtrToStringAnsi((IntPtr)stringColValue);table->Rows->Add(row);}
void CreateAndPopulateTable(){// Create a simple DataTable.table = gcnew DataTable("SampleTable");
// Add a column of type String to the table.DataColumn ^column1 = gcnew DataColumn("StringCol",Type::GetType("System.String"));table->Columns->Add(column1);}
int GetValuesForColumn(char *dataColumn, char **values,int valuesLength){// Marshal the name of the column to a managed// String.String ^columnStr = Marshal::PtrToStringAnsi((IntPtr)dataColumn);
// Get all rows in the table.array ^rows = table->Select();int len = rows->Length;len = (len > valuesLength) ? valuesLength : len;for (int i = 0; i <> table;};
#pragma unmanagedint main(){// Create a table and add a few rows to it.DatabaseClass *db = new DatabaseClass();db->CreateAndPopulateTable();db->AddRow("This is string 1.");db->AddRow("This is string 2.");
// Now retrieve the rows and display their contents.char *values[MAXCOLS];int len = db->GetValuesForColumn("StringCol", values, MAXCOLS);for (int i = 0; i <>
ExampleIn this example, the class DatabaseClass is created to interact with an ADO.NET DataTable object. Note that this class is a native C++ class (as compared to a ref class or value class). This is necessary because we want to use this class from native code, and you cannot use managed types in native code. This class will be compiled to target the CLR, as is indicated by the #pragma managed directive preceding the class declaration. For more information on this directive, see managed, unmanaged.
Note the private member of the DatabaseClass class: gcroot
The rest of the code in this example is native C++ code, as is indicated by the #pragma unmanaged directive preceding main. In this example, we are creating a new instance of DatabaseClass and calling its methods to create a table and populate some rows in the table. Note that native C++ strings are being passed as values for the database column StringCol. Inside DatabaseClass, these strings are marshaled to managed strings using the marshaling functionality found in the System.Runtime.InteropServices namespace. Specifically, the method PtrToStringAnsi is used to marshal a char * to a String, and the method StringToHGlobalAnsi is used to marshal a String to a char *.
Note The memory allocated by StringToHGlobalAnsi must be deallocated by calling either FreeHGlobal or GlobalFree.// adonet_marshal_string_native.cpp// compile with: /clr /FU System.dll /FU System.Data.dll /FU System.Xml.dll#include
#using
#define MAXCOLS 100
#pragma managedclass DatabaseClass{public:DatabaseClass() : table(nullptr) { }
void AddRow(char *stringColValue){// Add a row to the table.DataRow ^row = table->NewRow();row["StringCol"] = Marshal::PtrToStringAnsi((IntPtr)stringColValue);table->Rows->Add(row);}
void CreateAndPopulateTable(){// Create a simple DataTable.table = gcnew DataTable("SampleTable");
// Add a column of type String to the table.DataColumn ^column1 = gcnew DataColumn("StringCol",Type::GetType("System.String"));table->Columns->Add(column1);}
int GetValuesForColumn(char *dataColumn, char **values,int valuesLength){// Marshal the name of the column to a managed// String.String ^columnStr = Marshal::PtrToStringAnsi((IntPtr)dataColumn);
// Get all rows in the table.array
#pragma unmanagedint main(){// Create a table and add a few rows to it.DatabaseClass *db = new DatabaseClass();db->CreateAndPopulateTable();db->AddRow("This is string 1.");db->AddRow("This is string 2.");
// Now retrieve the rows and display their contents.char *values[MAXCOLS];int len = db->GetValuesForColumn("StringCol", values, MAXCOLS);for (int i = 0; i <>
/clr (Common Language Runtime Compilation)
/clr (Common Language Runtime Compilation)
Enables applications and components to use features from the common language runtime (CLR).
/clr[:options]
Arguments
options
One or more of the following, separated by a comma:
/clr
Creates metadata for your application that can be consumed by other CLR applications, and allows your application to consume types and data in the metadata of other CLR components.
For more information, see:
Mixed (Native and Managed) Assemblies
How To: Migrate to /clr
/clr:pure
Produces an MSIL-only output file with no native executable code, although it can contain native types compiled to MSIL.
For more information, see Pure and Verifiable Code.
/clr:safe
Produces an MSIL-only (no native executable code) and verifiable output file. /clr:safe enables verification diagnostics (PEVerify Tool (Peverify.exe)).
For more information, see Writing Verifiably Type-Safe Code.
/clr:oldSyntax
Enables Managed Extensions for C++ syntax, the original Visual C++ syntax for CLR programming.
Managed Extensions for C++ syntax is deprecated in Microsoft Visual C++ 2005, You should only use /clr:oldSyntax if you are maintaining a Visual C++ application that uses Managed Extensions for C++. If you are developing a new application, use the updated syntax; see New C++ Language Features for more information.
If you have a Managed Extensions for C++ application, you can begin to port your project to use the new syntax; see Porting and Upgrading Programs for more information.
/clr:noAssembly
Specifies that an assembly manifest should not be inserted into the output file. By default, noAssembly is not in effect, and an assembly manifest is inserted into the output file. A managed program that does not have an assembly metadata in the manifest is called a module. See /LN (Create MSIL Module) for reasons to generate a module.
noAssembly can only be used when a DLL is the output file of the compilation. If you compile with /c (Compile Without Linking) and /clr:noAssembly, then specify the /NOASSEMBLY (Create a MSIL Module) option in the linker phase to create a module.
noAssembly is deprecated in Visual C++ 2005. Use /LN (Create MSIL Module) instead. For more information, see Deprecated Compiler Options.
Before Visual C++ 2005, /clr:noAssembly implied /clr. However, /clr now also supports /clr:oldSyntax, so you must specify one /clr form when you specify /clr:noAssembly. For example, /clr:noAssembly /clr creates a module using the new Visual C++ CLR syntax and /clr:noAssembly,oldSyntax creates a module using Managed Extensions for C++.
Before Visual C++ 2005, /clr:noAssembly required /LD. /LD is now implied with you specify /clr:noAssembly.
/clr:initialAppDomain
Allows a Visual C++ application to run on version 1 of the common language runtime. If you use initialAppDomain, then you may see some of the problems discussed in Knowledge Base article Q309694. You can find Knowledge Base articles on the MSDN Library media or at http://support.microsoft.com/support/.
An application compiled with initialAppDomain should never be used by an application using ASP.NET. Upgrade to a newer runtime to do ASP.NET work with C++.
Enables applications and components to use features from the common language runtime (CLR).
/clr[:options]
Arguments
options
One or more of the following, separated by a comma:
/clr
Creates metadata for your application that can be consumed by other CLR applications, and allows your application to consume types and data in the metadata of other CLR components.
For more information, see:
Mixed (Native and Managed) Assemblies
How To: Migrate to /clr
/clr:pure
Produces an MSIL-only output file with no native executable code, although it can contain native types compiled to MSIL.
For more information, see Pure and Verifiable Code.
/clr:safe
Produces an MSIL-only (no native executable code) and verifiable output file. /clr:safe enables verification diagnostics (PEVerify Tool (Peverify.exe)).
For more information, see Writing Verifiably Type-Safe Code.
/clr:oldSyntax
Enables Managed Extensions for C++ syntax, the original Visual C++ syntax for CLR programming.
Managed Extensions for C++ syntax is deprecated in Microsoft Visual C++ 2005, You should only use /clr:oldSyntax if you are maintaining a Visual C++ application that uses Managed Extensions for C++. If you are developing a new application, use the updated syntax; see New C++ Language Features for more information.
If you have a Managed Extensions for C++ application, you can begin to port your project to use the new syntax; see Porting and Upgrading Programs for more information.
/clr:noAssembly
Specifies that an assembly manifest should not be inserted into the output file. By default, noAssembly is not in effect, and an assembly manifest is inserted into the output file. A managed program that does not have an assembly metadata in the manifest is called a module. See /LN (Create MSIL Module) for reasons to generate a module.
noAssembly can only be used when a DLL is the output file of the compilation. If you compile with /c (Compile Without Linking) and /clr:noAssembly, then specify the /NOASSEMBLY (Create a MSIL Module) option in the linker phase to create a module.
noAssembly is deprecated in Visual C++ 2005. Use /LN (Create MSIL Module) instead. For more information, see Deprecated Compiler Options.
Before Visual C++ 2005, /clr:noAssembly implied /clr. However, /clr now also supports /clr:oldSyntax, so you must specify one /clr form when you specify /clr:noAssembly. For example, /clr:noAssembly /clr creates a module using the new Visual C++ CLR syntax and /clr:noAssembly,oldSyntax creates a module using Managed Extensions for C++.
Before Visual C++ 2005, /clr:noAssembly required /LD. /LD is now implied with you specify /clr:noAssembly.
/clr:initialAppDomain
Allows a Visual C++ application to run on version 1 of the common language runtime. If you use initialAppDomain, then you may see some of the problems discussed in Knowledge Base article Q309694. You can find Knowledge Base articles on the MSDN Library media or at http://support.microsoft.com/support/.
An application compiled with initialAppDomain should never be used by an application using ASP.NET. Upgrade to a newer runtime to do ASP.NET work with C++.
/GS (Buffer Security Check)
Detects some buffer overruns that overwrite the return address, a common technique for exploiting code that does not enforce buffer size restrictions. This is achieved by injecting security checks into the compiled code.
/GS[-]
Remarks
/GS is on by default. Use /GS- if you expect your application to have no security exposure.
For additional information on /GS see Compiler Security Checks .
The compiler injects checks in functions with local string buffers or, on x86, functions with exception handling. A string buffer is defined as an array whose element size is one or two bytes, and where the size of the whole array is at least five bytes, or, any buffer allocated with _alloca.
On all platforms, the compiler injects a cookie to protect the function's return address if the function has local string buffers. This cookie is checked on function exit, and during frame unwinding on 64-bit operating systems or on x86 for functions with some form of exception handling. On x86, the compiler also injects a cookie to protect the address of the function's exception handler. This cookie is checked during frame unwinding.
/GS primarily attempts to detect direct buffer overruns into the return address. Buffer overruns are more easily exploited on machines with calling conventions that store the return address of function calls on the stack. For example, x86 uses calling conventions that store the return address of function calls on the stack.
On functions that the compiler thinks might be subject to buffer overrun problems, the compiler will allocate space on the stack before the return address. On function entry, the allocated space is loaded with a security cookie that is computed once at module load. Then, on function exit, a helper function is called to make sure the cookie's value is still the same.
If the value is not the same, an overwrite of the stack has potentially occurred and the process simply terminates. Prior to Visual C++ 2005 a dialog box displayed reporting the stack overwrite
/GS also protects against vulnerable parameters passed into a function. A vulnerable parameter is a pointer, C++ reference, or a C-structure (C++ POD type) that contains a pointer, string buffer, or C++ reference.
A vulnerable parameter is allocated before the cookie and local variables. A buffer overrun can overwrite these parameters. Code in the function that uses these parameters can lead to an attack before the function returns, thus avoiding the security check. To minimize this danger, the compiler will make a copy of the vulnerable parameters during the function prolog and put them below the storage area for any buffers.
The compiler does not provide security protection for vulnerable parameters in the following situations:
Functions that do not contain a buffer.
If optimizations (/O Options (Optimize Code)) are not enabled.
Functions with a variable argument list (...).
Functions marked with naked (C++).
Functions containing inline assembly code in the first statement.
If a parameter is used only in ways that are less likely to be exploitable in the event of a buffer overrun.
/GS requires initialization of the security cookie. This cookie must be initialized before any function using the cookie runs. The security cookie must be initialized upon entry to an EXE or DLL. This is done automatically when using the default CRT entry points (mainCRTStartup, wmainCRTStartup, WinMainCRTStartup, wWinMainCRTStartup, or _DllMainCRTStartup), but must be done manually, via a call to __security_init_cookie, if you use an alternate entry point.
/GS is supported for managed functions when compiling with /clr (Common Language Runtime Compilation).
/GS does not protect against all buffer overrun security attacks. For example, if you have a buffer and a vtable in an object, the buffer overrun could corrupt the vtable and allow an attack to occur.
Even if you use /GS, you should strive to write secure code. That is, make sure that your code has no buffer overruns. /GS might protect your application from buffer overruns that do remain in your code.
/GS[-]
Remarks
/GS is on by default. Use /GS- if you expect your application to have no security exposure.
For additional information on /GS see Compiler Security Checks .
The compiler injects checks in functions with local string buffers or, on x86, functions with exception handling. A string buffer is defined as an array whose element size is one or two bytes, and where the size of the whole array is at least five bytes, or, any buffer allocated with _alloca.
On all platforms, the compiler injects a cookie to protect the function's return address if the function has local string buffers. This cookie is checked on function exit, and during frame unwinding on 64-bit operating systems or on x86 for functions with some form of exception handling. On x86, the compiler also injects a cookie to protect the address of the function's exception handler. This cookie is checked during frame unwinding.
/GS primarily attempts to detect direct buffer overruns into the return address. Buffer overruns are more easily exploited on machines with calling conventions that store the return address of function calls on the stack. For example, x86 uses calling conventions that store the return address of function calls on the stack.
On functions that the compiler thinks might be subject to buffer overrun problems, the compiler will allocate space on the stack before the return address. On function entry, the allocated space is loaded with a security cookie that is computed once at module load. Then, on function exit, a helper function is called to make sure the cookie's value is still the same.
If the value is not the same, an overwrite of the stack has potentially occurred and the process simply terminates. Prior to Visual C++ 2005 a dialog box displayed reporting the stack overwrite
/GS also protects against vulnerable parameters passed into a function. A vulnerable parameter is a pointer, C++ reference, or a C-structure (C++ POD type) that contains a pointer, string buffer, or C++ reference.
A vulnerable parameter is allocated before the cookie and local variables. A buffer overrun can overwrite these parameters. Code in the function that uses these parameters can lead to an attack before the function returns, thus avoiding the security check. To minimize this danger, the compiler will make a copy of the vulnerable parameters during the function prolog and put them below the storage area for any buffers.
The compiler does not provide security protection for vulnerable parameters in the following situations:
Functions that do not contain a buffer.
If optimizations (/O Options (Optimize Code)) are not enabled.
Functions with a variable argument list (...).
Functions marked with naked (C++).
Functions containing inline assembly code in the first statement.
If a parameter is used only in ways that are less likely to be exploitable in the event of a buffer overrun.
/GS requires initialization of the security cookie. This cookie must be initialized before any function using the cookie runs. The security cookie must be initialized upon entry to an EXE or DLL. This is done automatically when using the default CRT entry points (mainCRTStartup, wmainCRTStartup, WinMainCRTStartup, wWinMainCRTStartup, or _DllMainCRTStartup), but must be done manually, via a call to __security_init_cookie, if you use an alternate entry point.
/GS is supported for managed functions when compiling with /clr (Common Language Runtime Compilation).
/GS does not protect against all buffer overrun security attacks. For example, if you have a buffer and a vtable in an object, the buffer overrun could corrupt the vtable and allow an attack to occur.
Even if you use /GS, you should strive to write secure code. That is, make sure that your code has no buffer overruns. /GS might protect your application from buffer overruns that do remain in your code.
/GR (Enable Run-Time Type Information)
Adds code to check object types at run time.
/GR[-]
Remarks
When /GR is on, the compiler defines the _CPPRTTI preprocessor macro. In Visual C++ 2005, /GR is on by default. /GR- disables run-time type information.
Use /GR if your code uses dynamic_cast Operator or typeid. /GR does, however, cause the .rdata sections of your image to increase in size. If your code does not use dynamic_cast or typeid, using /GR- may produce a smaller image.
For more information on run-time type checking, see Run-Time Type Information in the C++ Language Reference.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Language property page.
4. Modify the Enable Run-Time Type Info property.
/GR[-]
Remarks
When /GR is on, the compiler defines the _CPPRTTI preprocessor macro. In Visual C++ 2005, /GR is on by default. /GR- disables run-time type information.
Use /GR if your code uses dynamic_cast Operator or typeid. /GR does, however, cause the .rdata sections of your image to increase in size. If your code does not use dynamic_cast or typeid, using /GR- may produce a smaller image.
For more information on run-time type checking, see Run-Time Type Information in the C++ Language Reference.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Language property page.
4. Modify the Enable Run-Time Type Info property.
/LTCG (Link-time Code Generation)
/LTCG[:NOSTATUS:STATUS:PGINSTRUMENT:PGOPTIMIZE:PGUPDATE]
Remarks
where:
:NOSTATUS :STATUS (optional)
Specifies whether the linker should display a progress indicator showing what percentage of the link is complete. The default is to not display this status information.
:PGINSTRUMENT (optional)
Specifies that the linker should output a .pgd file in preparation for instrumented test runs on the application. You can optionally specify /PGD to create the .pgd file with a nondefault name or location.
The data collected from the instrumented runs will be used to create an optimized image. For more information, see Profile Guided Optimization. The short form of this option is /LTCG:PGI.
:PGOPTIMIZE (optional)
Specifies that the linker should use the profile data created after running the instrumented binary to create an optimized image. All input files must be identical to the files that were specified with /LTCG:PGI. For more information, see Profile Guided Optimization. The short form of this option is /LTCG:PGO.
:PGUPDATE (optional)
Allows list of input files to be added or modified from what was specified in the :PGINSTRUMENT phase. However, any new input files will not be optimized with profile-guided optimizations and changed portions of a modified input file that invalidate profile data collected during the instrumentation phase for that code will not be optimized with profile-guided optimizations. For more information, see Profile Guided Optimization. The short form of this option is /LTCG:PGU.
Remarks
The /LTCG option tells the linker to call the compiler and perform whole program optimization. You can also do profile guided optimization. For more information, see Profile Guided Optimization.
With the following exceptions, you cannot add additional linker options to the /LTCG:PGOPTIMIZE or /LTCG:PGUPDATE run that were not specified in the /LTCG:PGINSTRUMENT run:
/BASE
/FIXED
/LTCG
/MAP
/MAPINFO
/NOLOGO
/OUT
/PGD
/PDB
/PDBSTRIPPED
/STUB
/VERBOSE
Any linker options specified to /LTCG:PGINSTRUMENT do not have to be specified to /LTCG:PGOPTIMIZE; they are implied.
The rest of this topic will only discuss /LTGC in terms of link-time code generation.
/LTCG is implied with /GL.
The linker invokes link-time code generation if it is passed a module that was compiled with /GL or an MSIL module (see .netmodule Files as Linker Input for more information). If you do not explicitly specify /LTCG when passing /GL or MSIL modules to the linker, the linker will eventually detect this and restart the link with /LTCG. Explicitly specify /LTCG when passing /GL and MSIL modules to the linker for the fastest possible build performance.
/LTCG is not valid for use with /INCREMENTAL.
When /LTCG is used with either /Og, /O1, /O2, or /Ox, the following optimizations are performed:
Cross-module inlining
Interprocedural register allocation (64-bit operating systems only)
Custom calling convention (x86 only)
Small TLS displacement (x86 only)
Stack double alignment (x86 only)
Improved memory disambiguation (better interference information for global variables and input parameters)
Using /LTCG and /Ogt will result in double-alignment optimization.
If /LTCG and /Ogs are specified, double alignment will not be performed. If most of the functions in an application are compiled for speed, with a few functions compiled for size (for example, by using the optimize pragma), the compiler will double align these functions that are optimized for size if they call functions that need double alignment.
If the compiler can identify all the call sites of a function, the compiler will ignore explicit calling-convention modifiers on a function and try to optimize the function's calling convention:
pass parameters in registers
reorder parameters for alignment
remove unused parameters
If a function is called via function pointer, or if a function make be called outside of a module compiled with /GL, the compiler will not attempt to optimize a function's calling convention.
Note
If you use /LTCG and redefine mainCRTStartup, your application can have unpredictable behavior relating to user code that executes before global objects are initialized. There are three ways to address this issue: do not redefine mainCRTStartup, do not compile the file containing mainCRTStartup with /LTCG, or initialize global variables and objects statically, if possible.
/LTCG and MSIL Modules
Modules compiled with /GL and /clr can be used as input to the linker when /LTCG is specified:
/LTCG can accept native object files; mixed native/managed object files (compiled with /clr), pure object files (compiled with /clr:pure), and safe object files (compiled with /clr:safe)
/LTCG can accept safe .netmodules, which can be created with /clr:safe /LN in Visual C++ and /target:module with any other Visual Studio compiler. .netmodules produced with /clr or /clr:pure are not accepted by /LTCG.
/LTCG:PGI does not accept native modules compiled with /GL and /clr, or pure modules (produced with /clr:pure)
Remarks
where:
:NOSTATUS :STATUS (optional)
Specifies whether the linker should display a progress indicator showing what percentage of the link is complete. The default is to not display this status information.
:PGINSTRUMENT (optional)
Specifies that the linker should output a .pgd file in preparation for instrumented test runs on the application. You can optionally specify /PGD to create the .pgd file with a nondefault name or location.
The data collected from the instrumented runs will be used to create an optimized image. For more information, see Profile Guided Optimization. The short form of this option is /LTCG:PGI.
:PGOPTIMIZE (optional)
Specifies that the linker should use the profile data created after running the instrumented binary to create an optimized image. All input files must be identical to the files that were specified with /LTCG:PGI. For more information, see Profile Guided Optimization. The short form of this option is /LTCG:PGO.
:PGUPDATE (optional)
Allows list of input files to be added or modified from what was specified in the :PGINSTRUMENT phase. However, any new input files will not be optimized with profile-guided optimizations and changed portions of a modified input file that invalidate profile data collected during the instrumentation phase for that code will not be optimized with profile-guided optimizations. For more information, see Profile Guided Optimization. The short form of this option is /LTCG:PGU.
Remarks
The /LTCG option tells the linker to call the compiler and perform whole program optimization. You can also do profile guided optimization. For more information, see Profile Guided Optimization.
With the following exceptions, you cannot add additional linker options to the /LTCG:PGOPTIMIZE or /LTCG:PGUPDATE run that were not specified in the /LTCG:PGINSTRUMENT run:
/BASE
/FIXED
/LTCG
/MAP
/MAPINFO
/NOLOGO
/OUT
/PGD
/PDB
/PDBSTRIPPED
/STUB
/VERBOSE
Any linker options specified to /LTCG:PGINSTRUMENT do not have to be specified to /LTCG:PGOPTIMIZE; they are implied.
The rest of this topic will only discuss /LTGC in terms of link-time code generation.
/LTCG is implied with /GL.
The linker invokes link-time code generation if it is passed a module that was compiled with /GL or an MSIL module (see .netmodule Files as Linker Input for more information). If you do not explicitly specify /LTCG when passing /GL or MSIL modules to the linker, the linker will eventually detect this and restart the link with /LTCG. Explicitly specify /LTCG when passing /GL and MSIL modules to the linker for the fastest possible build performance.
/LTCG is not valid for use with /INCREMENTAL.
When /LTCG is used with either /Og, /O1, /O2, or /Ox, the following optimizations are performed:
Cross-module inlining
Interprocedural register allocation (64-bit operating systems only)
Custom calling convention (x86 only)
Small TLS displacement (x86 only)
Stack double alignment (x86 only)
Improved memory disambiguation (better interference information for global variables and input parameters)
Using /LTCG and /Ogt will result in double-alignment optimization.
If /LTCG and /Ogs are specified, double alignment will not be performed. If most of the functions in an application are compiled for speed, with a few functions compiled for size (for example, by using the optimize pragma), the compiler will double align these functions that are optimized for size if they call functions that need double alignment.
If the compiler can identify all the call sites of a function, the compiler will ignore explicit calling-convention modifiers on a function and try to optimize the function's calling convention:
pass parameters in registers
reorder parameters for alignment
remove unused parameters
If a function is called via function pointer, or if a function make be called outside of a module compiled with /GL, the compiler will not attempt to optimize a function's calling convention.
Note
If you use /LTCG and redefine mainCRTStartup, your application can have unpredictable behavior relating to user code that executes before global objects are initialized. There are three ways to address this issue: do not redefine mainCRTStartup, do not compile the file containing mainCRTStartup with /LTCG, or initialize global variables and objects statically, if possible.
/LTCG and MSIL Modules
Modules compiled with /GL and /clr can be used as input to the linker when /LTCG is specified:
/LTCG can accept native object files; mixed native/managed object files (compiled with /clr), pure object files (compiled with /clr:pure), and safe object files (compiled with /clr:safe)
/LTCG can accept safe .netmodules, which can be created with /clr:safe /LN in Visual C++ and /target:module with any other Visual Studio compiler. .netmodules produced with /clr or /clr:pure are not accepted by /LTCG.
/LTCG:PGI does not accept native modules compiled with /GL and /clr, or pure modules (produced with /clr:pure)
/CLRHEADER
/CLRHEADER file
Remarks
where:
file
An image file built with /clr.
Remarks
CLRHEADER displays information about the .NET headers used in any managed program. The output shows the location and size, in bytes, of the .NET header and sections in the header.
Only the /HEADERS DUMPBIN option is available for use on files produced with the /GL compiler option.
When /CLRHEADER is used on a file that was compiled with /clr, there will be a clr Header: section in the dumpbin output. The value of flags indicates which /clr option was used:
0 -- /clr (image may contain native code).
1 -- /clr:safe (image is MSIL only, able to run on any CLR platform, and possibly verifiable).
3 -- /clr:pure (image is MSIL only, but only able to run on x86 platforms).
You can also programmatically check if an image was built for the common language runtime. For more information, see How to: Determine if an Image is Native or CLR.
Remarks
where:
file
An image file built with /clr.
Remarks
CLRHEADER displays information about the .NET headers used in any managed program. The output shows the location and size, in bytes, of the .NET header and sections in the header.
Only the /HEADERS DUMPBIN option is available for use on files produced with the /GL compiler option.
When /CLRHEADER is used on a file that was compiled with /clr, there will be a clr Header: section in the dumpbin output. The value of flags indicates which /clr option was used:
0 -- /clr (image may contain native code).
1 -- /clr:safe (image is MSIL only, able to run on any CLR platform, and possibly verifiable).
3 -- /clr:pure (image is MSIL only, but only able to run on x86 platforms).
You can also programmatically check if an image was built for the common language runtime. For more information, see How to: Determine if an Image is Native or CLR.
/GL (Whole Program Optimization)
Enables whole program optimization.
/GL[-]
Remarks
Whole program optimization allows the compiler to perform optimizations with information on all modules in the program. Without whole program optimization, optimizations are performed on a per module (compiland) basis.
Whole program optimization is off by default and must be explicitly enabled. However, it is also possible to explicitly disable it with /GL-.
With information on all modules, the compiler can:
Optimize the use of registers across function boundaries.
Do a better job of tracking modifications to global data, allowing a reduction in the number of loads and stores.
Do a better job of tracking the possible set of items modified by a pointer dereference, reducing the numbers of loads and stores.
Inline a function in a module even when the function is defined in another module.
.obj files produced with /GL will not be available to such linker utilities as EDITBIN Reference and DUMPBIN Reference.
If you compile your program with /GL and /c (Compile Without Linking), you should use the /LTCG linker option to create the output file.
/Z7, /Zi, /ZI (Debug Information Format) cannot be used with /GL
The format of files produced with /GL in the current version may not be readable by subsequent versions of Visual C++. You should not ship a .lib file comprised of .obj files that were produced with /GL unless you are willing to ship copies of the .lib file for all versions of Visual C++ you expect your users to use, now and in the future.
.obj files produced with /GL and precompiled header files should not be used to build a .lib file unless the .lib file will be linked on the same machine that produced the /GL .obj file. Information from the .obj file's precompiled header file will be needed at link time.
For more information on the optimizations available with and the limitations of whole program optimization, see/LTCG (Link-time Code Generation). /GL also makes profile guided optimization available; see /LTCG. When compiling for profile guided optimizations and if you want function ordering from your profile guided optimizations, you must compile with /Gy (Enable Function-Level Linking) or a compiler option that implies /Gy.
/GL[-]
Remarks
Whole program optimization allows the compiler to perform optimizations with information on all modules in the program. Without whole program optimization, optimizations are performed on a per module (compiland) basis.
Whole program optimization is off by default and must be explicitly enabled. However, it is also possible to explicitly disable it with /GL-.
With information on all modules, the compiler can:
Optimize the use of registers across function boundaries.
Do a better job of tracking modifications to global data, allowing a reduction in the number of loads and stores.
Do a better job of tracking the possible set of items modified by a pointer dereference, reducing the numbers of loads and stores.
Inline a function in a module even when the function is defined in another module.
.obj files produced with /GL will not be available to such linker utilities as EDITBIN Reference and DUMPBIN Reference.
If you compile your program with /GL and /c (Compile Without Linking), you should use the /LTCG linker option to create the output file.
/Z7, /Zi, /ZI (Debug Information Format) cannot be used with /GL
The format of files produced with /GL in the current version may not be readable by subsequent versions of Visual C++. You should not ship a .lib file comprised of .obj files that were produced with /GL unless you are willing to ship copies of the .lib file for all versions of Visual C++ you expect your users to use, now and in the future.
.obj files produced with /GL and precompiled header files should not be used to build a .lib file unless the .lib file will be linked on the same machine that produced the /GL .obj file. Information from the .obj file's precompiled header file will be needed at link time.
For more information on the optimizations available with and the limitations of whole program optimization, see/LTCG (Link-time Code Generation). /GL also makes profile guided optimization available; see /LTCG. When compiling for profile guided optimizations and if you want function ordering from your profile guided optimizations, you must compile with /Gy (Enable Function-Level Linking) or a compiler option that implies /Gy.
/GF (Eliminate Duplicate Strings)
Enables the compiler to create a single copy of identical strings in the program image and in memory during execution, resulting in smaller programs, an optimization called string pooling.
/GF
Remarks
/GF pools strings as read-only.
If you use /GF, the operating system does not swap the string portion of memory and can read the strings back from the image file. If you try to modify strings under /GF, an application error occurs.
String pooling allows what were intended as multiple pointers to multiple buffers to be as multiple pointers to a single buffer. In the following code, s and t are initialized with the same string. String pooling causes them to point to the same memory:
char *s = "This is a character buffer";
char *t = "This is a character buffer";
Note
The/Z7, /Zi, /ZI (Debug Information Format) option, used for Edit and Continue, automatically sets the /GF option.
/GF is in effect when/O1, /O2 (Minimize Size, Maximize Speed) or /O2 is used.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Code Generation property page.
4. Modify the Enable String Pooling property.
/GF
Remarks
/GF pools strings as read-only.
If you use /GF, the operating system does not swap the string portion of memory and can read the strings back from the image file. If you try to modify strings under /GF, an application error occurs.
String pooling allows what were intended as multiple pointers to multiple buffers to be as multiple pointers to a single buffer. In the following code, s and t are initialized with the same string. String pooling causes them to point to the same memory:
char *s = "This is a character buffer";
char *t = "This is a character buffer";
Note
The/Z7, /Zi, /ZI (Debug Information Format) option, used for Edit and Continue, automatically sets the /GF option.
/GF is in effect when/O1, /O2 (Minimize Size, Maximize Speed) or /O2 is used.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Code Generation property page.
4. Modify the Enable String Pooling property.
/G (Optimize for Processor) Options
Tells the compiler to optimize code generation for the specified processor.
/G{12}
Arguments
/G1
Optimize for Itanium processor. Only available in the Itanium cross compiler or Itanium native compiler.
/G2
Optimize for Itanium2 processor (default between /G1 and /G2) Only available in the Itanium cross compiler or Itanium native compiler.
/G is available in all editions of Visual C++, but the compiler can perform more optimizations when /G is used with one of the /O compiler options. However, /O is not available in the Visual C++ standard edition.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Command Line property page.
4. Type the compiler option in the Additional Options box.
/G{12}
Arguments
/G1
Optimize for Itanium processor. Only available in the Itanium cross compiler or Itanium native compiler.
/G2
Optimize for Itanium2 processor (default between /G1 and /G2) Only available in the Itanium cross compiler or Itanium native compiler.
/G is available in all editions of Visual C++, but the compiler can perform more optimizations when /G is used with one of the /O compiler options. However, /O is not available in the Visual C++ standard edition.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Command Line property page.
4. Type the compiler option in the Additional Options box.
/fp (Specify Floating-Point Behavior)
Specifies floating-point behavior in a source code file.
/fp:[precise except[-] fast strict ]
Flags
precise
The default.
Improves the consistency of floating-point tests for equality and inequality by disabling optimizations that could change the precision of floating-point calculations, which is required for strict ANSI conformance. By default, the compiler uses the coprocessor's 80-bit registers to hold the intermediate results of floating-point calculations. This increases program speed and decreases program size. Because the calculation involves floating-point data types that are represented in memory by less than 80 bits, however, carrying the extra bits of precision (80 bits minus the number of bits in a smaller floating-point type) through a lengthy calculation can produce inconsistent results.
With /fp:precise on x86 processors, the compiler will perform rounding on variables of type float to the proper precision for assignments and casts and when passing parameters to a function. This rounding guarantees that the data does not retain any significance greater than the capacity of its type. A program compiled with /fp:precise can be slower and larger than one compiled without /fp:precise. /fp:precise disables intrinsics; the standard run-time library routines are used instead. For more information, see /Oi (Generate Intrinsic Functions).
The following floating-point behavior is enabled with /fp:precise:
Contractions, or replacing multiple operations with one composite operation with only a single rounding at the end, is enabled with /fp:precise.
Expression optimizations that are invalid for special values (NaN, +infinity, -infinity, +0, -0) will not be allowed. The optimizations x-x => 0, x*0 => 0, x-0 => x, x+0 => x, and 0-x => -x are all invalid for various reasons (see IEEE 754 and the C99 standard).
The compiler will properly handle comparisons involving NaN. For example, x != x evaluates to true if x is NaN and ordered comparisons involving NaN raise an exception.
Expression evaluation will follow the C99 FLT_EVAL_METHOD=2, with one exception. When programming for x86 processors, because the FPU is set to 53-bit precision, this will be considered long double precision.
Multiplication by exactly 1.0 transformed into a use of the other factor. x*y*1.0 is transformed into x*y. Similarly, x*1.0*y is transformed into x*y.
Division by exactly 1.0 is transformed into a use of the dividend. x*y/1.0 is transformed into x*y. Similarly, x/1.0*y is transformed into x*y.
Using /fp:precise with fenv_access ON disables some optimizations such as compile-time evaluations of floating point expressions. For example, if you change rounding mode with _control87, _controlfp, __control87_2, and the compiler performs a floating-point calculation, the rounding mode you specified will not be in effect unless fenv_access is ON.
/fp:precise replaces the /Op compiler option.
fast
Creates the fastest code in the majority of cases. /fp:fast cannot be used with /fp:strict or /fp:precise, the last option specified on the command line will be used. /fp:fast and /fp:except will generate a compiler error.
Selecting /Za, /Ze (Disable Language Extensions) (ANSI compatibility) and /fp:fast may result in unexpected behavior. For example, single-precision floating-point operations may not be rounded to single precision.
except[-]
Reliable floating-point exception model. Exceptions will be raised immediately after they are triggered. This option is off by default. Appending a minus sign to the option explicitly disables it.
strict
The strictest floating-point model. /fp:strict causes fp_contract to be OFF and fenv_access to be ON. /fp:except is implied and can be disabled by explicitly specifying /fp:except-. When used with /fp:except-, /fp:strict enforces strict floating-point semantics but without respect for exceptional events.
Remarks
Multiple /fp options can be specified in the same compilation.
To control floating-point behavior by function, see the float_control pragma.
Most of the floating-point optimizations related to /fp:strict, /fp:except (and its corresponding pragmas), and fp_contract pragma are machine dependent. /fp:strict and /fp:except are not compatible with /clr.
/fp:precise should address most of an application's floating-point requirements. If necessary, you can use /fp:except and /fp:strict, but there may be some decrease in performance. If performance is most important, you may want to use /fp:fast.
fp:strict, /fp:fast, and /fp:precise are precision (correctness) modes. Only one can be in effect at a time. If /fp:strict and /fp:precise are specified, the compiler use the one that it processes last. You cannot specify both /fp:strict and /fp:fast.
/fp:[precise except[-] fast strict ]
Flags
precise
The default.
Improves the consistency of floating-point tests for equality and inequality by disabling optimizations that could change the precision of floating-point calculations, which is required for strict ANSI conformance. By default, the compiler uses the coprocessor's 80-bit registers to hold the intermediate results of floating-point calculations. This increases program speed and decreases program size. Because the calculation involves floating-point data types that are represented in memory by less than 80 bits, however, carrying the extra bits of precision (80 bits minus the number of bits in a smaller floating-point type) through a lengthy calculation can produce inconsistent results.
With /fp:precise on x86 processors, the compiler will perform rounding on variables of type float to the proper precision for assignments and casts and when passing parameters to a function. This rounding guarantees that the data does not retain any significance greater than the capacity of its type. A program compiled with /fp:precise can be slower and larger than one compiled without /fp:precise. /fp:precise disables intrinsics; the standard run-time library routines are used instead. For more information, see /Oi (Generate Intrinsic Functions).
The following floating-point behavior is enabled with /fp:precise:
Contractions, or replacing multiple operations with one composite operation with only a single rounding at the end, is enabled with /fp:precise.
Expression optimizations that are invalid for special values (NaN, +infinity, -infinity, +0, -0) will not be allowed. The optimizations x-x => 0, x*0 => 0, x-0 => x, x+0 => x, and 0-x => -x are all invalid for various reasons (see IEEE 754 and the C99 standard).
The compiler will properly handle comparisons involving NaN. For example, x != x evaluates to true if x is NaN and ordered comparisons involving NaN raise an exception.
Expression evaluation will follow the C99 FLT_EVAL_METHOD=2, with one exception. When programming for x86 processors, because the FPU is set to 53-bit precision, this will be considered long double precision.
Multiplication by exactly 1.0 transformed into a use of the other factor. x*y*1.0 is transformed into x*y. Similarly, x*1.0*y is transformed into x*y.
Division by exactly 1.0 is transformed into a use of the dividend. x*y/1.0 is transformed into x*y. Similarly, x/1.0*y is transformed into x*y.
Using /fp:precise with fenv_access ON disables some optimizations such as compile-time evaluations of floating point expressions. For example, if you change rounding mode with _control87, _controlfp, __control87_2, and the compiler performs a floating-point calculation, the rounding mode you specified will not be in effect unless fenv_access is ON.
/fp:precise replaces the /Op compiler option.
fast
Creates the fastest code in the majority of cases. /fp:fast cannot be used with /fp:strict or /fp:precise, the last option specified on the command line will be used. /fp:fast and /fp:except will generate a compiler error.
Selecting /Za, /Ze (Disable Language Extensions) (ANSI compatibility) and /fp:fast may result in unexpected behavior. For example, single-precision floating-point operations may not be rounded to single precision.
except[-]
Reliable floating-point exception model. Exceptions will be raised immediately after they are triggered. This option is off by default. Appending a minus sign to the option explicitly disables it.
strict
The strictest floating-point model. /fp:strict causes fp_contract to be OFF and fenv_access to be ON. /fp:except is implied and can be disabled by explicitly specifying /fp:except-. When used with /fp:except-, /fp:strict enforces strict floating-point semantics but without respect for exceptional events.
Remarks
Multiple /fp options can be specified in the same compilation.
To control floating-point behavior by function, see the float_control pragma.
Most of the floating-point optimizations related to /fp:strict, /fp:except (and its corresponding pragmas), and fp_contract pragma are machine dependent. /fp:strict and /fp:except are not compatible with /clr.
/fp:precise should address most of an application's floating-point requirements. If necessary, you can use /fp:except and /fp:strict, but there may be some decrease in performance. If performance is most important, you may want to use /fp:fast.
fp:strict, /fp:fast, and /fp:precise are precision (correctness) modes. Only one can be in effect at a time. If /fp:strict and /fp:precise are specified, the compiler use the one that it processes last. You cannot specify both /fp:strict and /fp:fast.
/FC (Full Path of Source Code File in Diagnostics)
Causes the compiler to display the full path of source code files passed to the compiler in diagnostics.
/FC
Remarks
Consider the following code sample:
// compiler_option_FC.cpp
int main( ) {
int i // C2143
}
Without /FC, the diagnostic text would look similar to this diagnostic text:
compiler_option_FC.cpp(5) : error C2143: syntax error : missing ';' before '}'
With /FC, the diagnostic text would look similar to this diagnostic text:
c:\test\compiler_option_FC.cpp(5) : error C2143: syntax error : missing ';' before '}'
/FC is also needed if you want to see the full path of a file name when using the __FILE__ macro. See Predefined Macros for more information on __FILE__.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Expand the Configuration Properties node.
3. Expand the C/C++ node.
4. Select the Advanced property page.
5. Modify the Use Full Paths property.
/FC
Remarks
Consider the following code sample:
// compiler_option_FC.cpp
int main( ) {
int i // C2143
}
Without /FC, the diagnostic text would look similar to this diagnostic text:
compiler_option_FC.cpp(5) : error C2143: syntax error : missing ';' before '}'
With /FC, the diagnostic text would look similar to this diagnostic text:
c:\test\compiler_option_FC.cpp(5) : error C2143: syntax error : missing ';' before '}'
/FC is also needed if you want to see the full path of a file name when using the __FILE__ macro. See Predefined Macros for more information on __FILE__.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Expand the Configuration Properties node.
3. Expand the C/C++ node.
4. Select the Advanced property page.
5. Modify the Use Full Paths property.
/FA, /Fa (Listing File)
Creates a listing file containing assembly code.
/FA[csu]
/Fapathname
Remarks
The arguments control the generation of source code and machine code and the extension of the listing file.
/favor:AMD64 optimizes the generated code for the AMD Opteron, and Athlon processors supporting 64-bit extensions, typically resulting in better performance for that platform. The resulting code can run on all x64 compatible platforms. Code generated with /favor:AMD64 could result in worse performance on Intel processors supporting EM64T.
The following table describes the various values to /FA. It is possible to specify more than one value to /FA. For example, you can specify /FAsu.
/FA = Assembly code; .asm
/FAc = Machine and assembly code; .cod
/FAs = Source and assembly code; .asm If /FAcs is specified, the file extension will be .cod
/FAu = Causes the output file to be created in UTF-8 format, with a byte order marker. By default, the file encoding is ANSI, but use /FAu if you want a listing file that displays correctly on any system, or if you are using Unicode source code files as input to the compiler.
If /FAsu is specified, and if a source code file uses Unicode encoding other than UTF-8, then the code lines in the .asm file may not display correctly.
By default, the listing file gets the same base name as the source file. You can change the name of the listing file and the directory where it is created using the /Fa option.
/Fa = One source_file.asm is created for each source code file in the compilation.
/Fafilename = filename.asm is placed in the current directory. Only valid when compiling a single source code file.
/Fafilename.extension = filename.extension is placed in the current directory. Only valid when compiling a single source code file.
/Fadirectory\ = One source_file.asm is created and placed in the specified directory for each source code file in the compilation. Note the required trailing backslash. Only paths on the current disk are allowed.
/Fadirectory\filename = filename.asm is placed in the specified directory. Only valid when compiling a single source code file.
/Fadirectory\filename.extension = filename.extension is placed in the specified directory. Only valid when compiling a single source code file.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see Setting Visual C++ Project Properties.
2. Click the C/C++ folder.
3. Click the Output Files property page.
4. Modify the ASM List Location (/Fa) or Assembler Output (/FA) property (/FAu must be specified in the Command Line property page, Additional Options box..
/FA[csu]
/Fapathname
Remarks
The arguments control the generation of source code and machine code and the extension of the listing file.
/favor:AMD64 optimizes the generated code for the AMD Opteron, and Athlon processors supporting 64-bit extensions, typically resulting in better performance for that platform. The resulting code can run on all x64 compatible platforms. Code generated with /favor:AMD64 could result in worse performance on Intel processors supporting EM64T.
The following table describes the various values to /FA. It is possible to specify more than one value to /FA. For example, you can specify /FAsu.
/FA = Assembly code; .asm
/FAc = Machine and assembly code; .cod
/FAs = Source and assembly code; .asm If /FAcs is specified, the file extension will be .cod
/FAu = Causes the output file to be created in UTF-8 format, with a byte order marker. By default, the file encoding is ANSI, but use /FAu if you want a listing file that displays correctly on any system, or if you are using Unicode source code files as input to the compiler.
If /FAsu is specified, and if a source code file uses Unicode encoding other than UTF-8, then the code lines in the .asm file may not display correctly.
By default, the listing file gets the same base name as the source file. You can change the name of the listing file and the directory where it is created using the /Fa option.
/Fa = One source_file.asm is created for each source code file in the compilation.
/Fafilename = filename.asm is placed in the current directory. Only valid when compiling a single source code file.
/Fafilename.extension = filename.extension is placed in the current directory. Only valid when compiling a single source code file.
/Fadirectory\ = One source_file.asm is created and placed in the specified directory for each source code file in the compilation. Note the required trailing backslash. Only paths on the current disk are allowed.
/Fadirectory\filename = filename.asm is placed in the specified directory. Only valid when compiling a single source code file.
/Fadirectory\filename.extension = filename.extension is placed in the specified directory. Only valid when compiling a single source code file.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see Setting Visual C++ Project Properties.
2. Click the C/C++ folder.
3. Click the Output Files property page.
4. Modify the ASM List Location (/Fa) or Assembler Output (/FA) property (/FAu must be specified in the Command Line property page, Additional Options box..
/favor (Optimize for 64)
/favor:option is available only in the x64 compiler and produces the code that is optimized for a specific x64 architecture or for the specifics of micro-architectures in both the AMD64 and Extended Memory 64 Technology (EM64T) architectures.
/favor:blend
/favor:AMD64
/favor:EM64T
Remarks
/favor:blend produces the code that is optimized for the specifics of micro-architectures in both the AMD64 and EM64T architectures. While /favor:blend may not give the best performance possible on a specific processor, it is designed to give the best performance across a broad range of x64 processors. /favor:blend is in effect by default.
/favor:AMD64 optimizes the generated code for the AMD Opteron, and Athlon processors supporting 64-bit extensions, typically resulting in better performance for that platform. The resulting code can run on all x64 compatible platforms. Code generated with /favor:AMD64 could result in worse performance on Intel processors supporting EM64T.
/favor:EM64T is available only in the x64 compiler and optimizes the generated code for Intel processors supporting EM64T, typically resulting in better performance for that platform. The resulting code can run on any x64 platform. Code generated with /favor:EM64T could result in worse performance on AMD Opteron, and Athlon processors supporting 64-bit extensions.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Command Line property page.
4. Type the compiler option in the Additional Options box.
/favor:blend
/favor:AMD64
/favor:EM64T
Remarks
/favor:blend produces the code that is optimized for the specifics of micro-architectures in both the AMD64 and EM64T architectures. While /favor:blend may not give the best performance possible on a specific processor, it is designed to give the best performance across a broad range of x64 processors. /favor:blend is in effect by default.
/favor:AMD64 optimizes the generated code for the AMD Opteron, and Athlon processors supporting 64-bit extensions, typically resulting in better performance for that platform. The resulting code can run on all x64 compatible platforms. Code generated with /favor:AMD64 could result in worse performance on Intel processors supporting EM64T.
/favor:EM64T is available only in the x64 compiler and optimizes the generated code for Intel processors supporting EM64T, typically resulting in better performance for that platform. The resulting code can run on any x64 platform. Code generated with /favor:EM64T could result in worse performance on AMD Opteron, and Athlon processors supporting 64-bit extensions.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Command Line property page.
4. Type the compiler option in the Additional Options box.
/errorReport (Report Internal Compiler Errors)
Allows you to provide internal compiler error (ICE) information directly to the Visual C++ team.
/errorReport:[ none prompt queue send ]
Arguments
none
Reports about internal compiler errors will not be collected or sent to Microsoft.
prompt
Prompts you to send a report when you receive an internal compiler error. prompt is the default when compiling an application in the development environment.
queue
Queues the error report. When you log in with administrator privileges, a pop-up window is displayed and allows you to report any failures since the last time you were logged in (you will not be prompted to send reports for failures more than once every three days). queue is the default when compiling an application at the command line.
send
Automatically sends reports of internal compiler errors to Microsoft. To enable this option, you must first agree to Microsoft’s data collection policy. The first time you specify /errorReport:send on a computer, a compiler message will refer you to a website that contains Microsoft’s data collection policy.
Remarks
An internal compiler error (ICE) results when the compiler cannot process a source code file. When an ICE occurs, the compiler does not produce an output file or any useful diagnostic that you can use to fix your code.
In previous releases, when you got an ICE, you were encouraged to call Microsoft technical support to report the problem. With /errorReport, you can provide ICE information directly to the Visual C++ team. Your error reports can help improve future compiler releases.
A user's ability to send reports depends on machine and user policy permissions.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For more information, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Advanced property page.
4. Modify the Error Reporting property.
/errorReport:[ none prompt queue send ]
Arguments
none
Reports about internal compiler errors will not be collected or sent to Microsoft.
prompt
Prompts you to send a report when you receive an internal compiler error. prompt is the default when compiling an application in the development environment.
queue
Queues the error report. When you log in with administrator privileges, a pop-up window is displayed and allows you to report any failures since the last time you were logged in (you will not be prompted to send reports for failures more than once every three days). queue is the default when compiling an application at the command line.
send
Automatically sends reports of internal compiler errors to Microsoft. To enable this option, you must first agree to Microsoft’s data collection policy. The first time you specify /errorReport:send on a computer, a compiler message will refer you to a website that contains Microsoft’s data collection policy.
Remarks
An internal compiler error (ICE) results when the compiler cannot process a source code file. When an ICE occurs, the compiler does not produce an output file or any useful diagnostic that you can use to fix your code.
In previous releases, when you got an ICE, you were encouraged to call Microsoft technical support to report the problem. With /errorReport, you can provide ICE information directly to the Visual C++ team. Your error reports can help improve future compiler releases.
A user's ability to send reports depends on machine and user policy permissions.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For more information, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Advanced property page.
4. Modify the Error Reporting property.
/EH (Exception Handling Model)
Specifies the model of exception handling to be used by the compiler.
/EH{sa}[c][-]
Arguments
a
The exception-handling model that catches asynchronous (structured) exceptions and tells the compiler to assume that extern C functions do throw an exception.
s
The exception-handling model that does not catch asynchronous exceptions and tells the compiler to assume that extern C functions do throw an exception.
c
If used with a, the exception-handling model that catches asynchronous exceptions. If used with s, the exception-handling model that does not catch asynchronous exceptions. In both cases, c tells the compiler to assume that extern C functions never throw an exception
Remarks
Use /EHs to specify the synchronous exception handling model (C++ exception handling without structured exception handling exceptions). If you use /EHs, then your catch clause will not catch asynchronous exceptions. Also, in Visual C++ 2005, all objects in scope when the asynchronous exception is generated will not be destroyed even if the asynchronous exception is handled. Under /EHs, catch(...) will only catch C++ exceptions. Access violations and System.Exception exceptions will not be caught.
Use /EHa to specify the asynchronous exception handling model (C++ exception handling with structured exception handling exceptions). /EHa may result in a less performant image because the compiler will not optimize a catch block as aggressively, even if the compiler does not see a throw.
Use /EHa if you want to catch an exception raised with something other than a throw. The following sample will generate an exception:
// compiler_options_EHA.cpp
// compile with: /EHa
#include
#include
using namespace std;
void fail() { // generates SE and attempts to catch it using catch(...)
try {
int i = 0, j = 1;
j /= i; // This will throw a SE (divide by zero).
}
catch(...) { // catch block will only be executed under /EHa
cout<<"Caught an exception in catch(...)."< } } int main() { __try { fail(); } // __except will only catch an exception here __except(EXCEPTION_EXECUTE_HANDLER) { // if the exception was not caught by the catch(...) inside fail() cout << "An exception was caught in __except." <<>
/EH{sa}[c][-]
Arguments
a
The exception-handling model that catches asynchronous (structured) exceptions and tells the compiler to assume that extern C functions do throw an exception.
s
The exception-handling model that does not catch asynchronous exceptions and tells the compiler to assume that extern C functions do throw an exception.
c
If used with a, the exception-handling model that catches asynchronous exceptions. If used with s, the exception-handling model that does not catch asynchronous exceptions. In both cases, c tells the compiler to assume that extern C functions never throw an exception
Remarks
Use /EHs to specify the synchronous exception handling model (C++ exception handling without structured exception handling exceptions). If you use /EHs, then your catch clause will not catch asynchronous exceptions. Also, in Visual C++ 2005, all objects in scope when the asynchronous exception is generated will not be destroyed even if the asynchronous exception is handled. Under /EHs, catch(...) will only catch C++ exceptions. Access violations and System.Exception exceptions will not be caught.
Use /EHa to specify the asynchronous exception handling model (C++ exception handling with structured exception handling exceptions). /EHa may result in a less performant image because the compiler will not optimize a catch block as aggressively, even if the compiler does not see a throw.
Use /EHa if you want to catch an exception raised with something other than a throw. The following sample will generate an exception:
// compiler_options_EHA.cpp
// compile with: /EHa
#include
#include
using namespace std;
void fail() { // generates SE and attempts to catch it using catch(...)
try {
int i = 0, j = 1;
j /= i; // This will throw a SE (divide by zero).
}
catch(...) { // catch block will only be executed under /EHa
cout<<"Caught an exception in catch(...)."< } } int main() { __try { fail(); } // __except will only catch an exception here __except(EXCEPTION_EXECUTE_HANDLER) { // if the exception was not caught by the catch(...) inside fail() cout << "An exception was caught in __except." <<>
Double Thunking (C++)
Double thunking refers to the loss of performance you can experience when a function call in a managed context calls a C++ managed function and where program execution calls the function's native entry point in order to call the managed function. This topic discusses where double thunking occurs and how you can avoid it to improve performance.
Remarks
By default, when compiling with /clr (not /clr:pure), the definition of a managed function causes the compiler to generate a managed entry point and a native entry point. This allows the managed function to be called from native and managed call sites. However, when a native entry point exists, it can be the entry point for all calls to the function. If a calling function is managed, the native entry point will then call the managed entry point. In effect, two calls are required to invoke the function (hence, double thunking). For example, virtual functions are always called through a native entry point.
One resolution is to tell the compiler not to generate a native entry point for a managed function, that the function will only be called from a managed context, by using the __clrcall calling convention.
Similarly, if you export (dllexport, dllimport) a managed function, a native entry point is generated and any function that imports and calls that function will call through the native entry point. To avoid double thunking in this situation, do not use native export/import semantics; simply reference the metadata via #using (see The #using Directive).
In Visual C++ 2005 the compiler was updated to reduce unnecessary double thunking. For example, any function with a managed type in the signature (including return type) will implicitly be marked as __clrcall. For more information on double thunk elimination
Example
The following sample demonstrates double thunking. When compiled native (without /clr), the call to the virtual function in main generates one call to T's copy constructor and one call to the destructor. Similar behavior is achieved when the virtual function is declared with /clr and __clrcall. However, when just compiled with /clr, the function call generates a call to the copy constructor but there is another call to the copy constructor due to the native-to-managed thunk.
// double_thunking.cpp
// compile with: /clr
#include
struct T {
T() {
puts(__FUNCSIG__);
}
T(const T&) {
puts(__FUNCSIG__);
}
~T() {
puts(__FUNCSIG__);
}
T& operator=(const T&) {
puts(__FUNCSIG__);
return *this;
}
};
struct S {
virtual void /* __clrcall */ f(T t) {};
} s;
int main() {
S* pS = &s;
T t;
printf("calling struct S\n");
pS->f(t);
printf("after calling struct S\n");
}
Sample Output
__thiscall T::T(void)
calling struct S
__thiscall T::T(const struct T &)
__thiscall T::T(const struct T &)
__thiscall T::~T(void)
__thiscall T::~T(void)
after calling struct S
__thiscall T::~T(void)
Remarks
By default, when compiling with /clr (not /clr:pure), the definition of a managed function causes the compiler to generate a managed entry point and a native entry point. This allows the managed function to be called from native and managed call sites. However, when a native entry point exists, it can be the entry point for all calls to the function. If a calling function is managed, the native entry point will then call the managed entry point. In effect, two calls are required to invoke the function (hence, double thunking). For example, virtual functions are always called through a native entry point.
One resolution is to tell the compiler not to generate a native entry point for a managed function, that the function will only be called from a managed context, by using the __clrcall calling convention.
Similarly, if you export (dllexport, dllimport) a managed function, a native entry point is generated and any function that imports and calls that function will call through the native entry point. To avoid double thunking in this situation, do not use native export/import semantics; simply reference the metadata via #using (see The #using Directive).
In Visual C++ 2005 the compiler was updated to reduce unnecessary double thunking. For example, any function with a managed type in the signature (including return type) will implicitly be marked as __clrcall. For more information on double thunk elimination
Example
The following sample demonstrates double thunking. When compiled native (without /clr), the call to the virtual function in main generates one call to T's copy constructor and one call to the destructor. Similar behavior is achieved when the virtual function is declared with /clr and __clrcall. However, when just compiled with /clr, the function call generates a call to the copy constructor but there is another call to the copy constructor due to the native-to-managed thunk.
// double_thunking.cpp
// compile with: /clr
#include
struct T {
T() {
puts(__FUNCSIG__);
}
T(const T&) {
puts(__FUNCSIG__);
}
~T() {
puts(__FUNCSIG__);
}
T& operator=(const T&) {
puts(__FUNCSIG__);
return *this;
}
};
struct S {
virtual void /* __clrcall */ f(T t) {};
} s;
int main() {
S* pS = &s;
T t;
printf("calling struct S\n");
pS->f(t);
printf("after calling struct S\n");
}
Sample Output
__thiscall T::T(void)
calling struct S
__thiscall T::T(const struct T &)
__thiscall T::T(const struct T &)
__thiscall T::~T(void)
__thiscall T::~T(void)
after calling struct S
__thiscall T::~T(void)
/clr (Common Language Runtime Compilation)
Enables applications and components to use features from the common language runtime (CLR).
/clr[:options]
Arguments
options
One or more of the following, separated by a comma:
/clr
Creates metadata for your application that can be consumed by other CLR applications, and allows your application to consume types and data in the metadata of other CLR components.
For more information, see:
Mixed (Native and Managed) Assemblies
How To: Migrate to /clr
/clr:pure
Produces an MSIL-only output file with no native executable code, although it can contain native types compiled to MSIL.
For more information, see Pure and Verifiable Code.
/clr:safe
Produces an MSIL-only (no native executable code) and verifiable output file. /clr:safe enables verification diagnostics (PEVerify Tool (Peverify.exe)).
For more information, see Writing Verifiably Type-Safe Code.
/clr:oldSyntax
Enables Managed Extensions for C++ syntax, the original Visual C++ syntax for CLR programming.
Managed Extensions for C++ syntax is deprecated in Microsoft Visual C++ 2005, You should only use /clr:oldSyntax if you are maintaining a Visual C++ application that uses Managed Extensions for C++. If you are developing a new application, use the updated syntax; see New C++ Language Features for more information.
If you have a Managed Extensions for C++ application, you can begin to port your project to use the new syntax; see Porting and Upgrading Programs for more information.
/clr:noAssembly
Specifies that an assembly manifest should not be inserted into the output file. By default, noAssembly is not in effect, and an assembly manifest is inserted into the output file.
A managed program that does not have an assembly metadata in the manifest is called a module. See /LN (Create MSIL Module) for reasons to generate a module.
noAssembly can only be used when a DLL is the output file of the compilation. If you compile with /c (Compile Without Linking) and /clr:noAssembly, then specify the /NOASSEMBLY (Create a MSIL Module) option in the linker phase to create a module.
noAssembly is deprecated in Visual C++ 2005. Use /LN (Create MSIL Module) instead. For more information, see Deprecated Compiler Options.
Before Visual C++ 2005, /clr:noAssembly implied /clr. However, /clr now also supports /clr:oldSyntax, so you must specify one /clr form when you specify /clr:noAssembly. For example, /clr:noAssembly /clr creates a module using the new Visual C++ CLR syntax and /clr:noAssembly,oldSyntax creates a module using Managed Extensions for C++.
Before Visual C++ 2005, /clr:noAssembly required /LD. /LD is now implied with you specify /clr:noAssembly.
/clr:initialAppDomain
Allows a Visual C++ application to run on version 1 of the common language runtime. If you use initialAppDomain, then you may see some of the problems discussed in Knowledge Base article Q309694. You can find Knowledge Base articles on the MSDN Library media or at http://support.microsoft.com/support/.
An application compiled with initialAppDomain should never be used by an application using ASP.NET. Upgrade to a newer runtime to do ASP.NET work with C++.
/clr[:options]
Arguments
options
One or more of the following, separated by a comma:
/clr
Creates metadata for your application that can be consumed by other CLR applications, and allows your application to consume types and data in the metadata of other CLR components.
For more information, see:
Mixed (Native and Managed) Assemblies
How To: Migrate to /clr
/clr:pure
Produces an MSIL-only output file with no native executable code, although it can contain native types compiled to MSIL.
For more information, see Pure and Verifiable Code.
/clr:safe
Produces an MSIL-only (no native executable code) and verifiable output file. /clr:safe enables verification diagnostics (PEVerify Tool (Peverify.exe)).
For more information, see Writing Verifiably Type-Safe Code.
/clr:oldSyntax
Enables Managed Extensions for C++ syntax, the original Visual C++ syntax for CLR programming.
Managed Extensions for C++ syntax is deprecated in Microsoft Visual C++ 2005, You should only use /clr:oldSyntax if you are maintaining a Visual C++ application that uses Managed Extensions for C++. If you are developing a new application, use the updated syntax; see New C++ Language Features for more information.
If you have a Managed Extensions for C++ application, you can begin to port your project to use the new syntax; see Porting and Upgrading Programs for more information.
/clr:noAssembly
Specifies that an assembly manifest should not be inserted into the output file. By default, noAssembly is not in effect, and an assembly manifest is inserted into the output file.
A managed program that does not have an assembly metadata in the manifest is called a module. See /LN (Create MSIL Module) for reasons to generate a module.
noAssembly can only be used when a DLL is the output file of the compilation. If you compile with /c (Compile Without Linking) and /clr:noAssembly, then specify the /NOASSEMBLY (Create a MSIL Module) option in the linker phase to create a module.
noAssembly is deprecated in Visual C++ 2005. Use /LN (Create MSIL Module) instead. For more information, see Deprecated Compiler Options.
Before Visual C++ 2005, /clr:noAssembly implied /clr. However, /clr now also supports /clr:oldSyntax, so you must specify one /clr form when you specify /clr:noAssembly. For example, /clr:noAssembly /clr creates a module using the new Visual C++ CLR syntax and /clr:noAssembly,oldSyntax creates a module using Managed Extensions for C++.
Before Visual C++ 2005, /clr:noAssembly required /LD. /LD is now implied with you specify /clr:noAssembly.
/clr:initialAppDomain
Allows a Visual C++ application to run on version 1 of the common language runtime. If you use initialAppDomain, then you may see some of the problems discussed in Knowledge Base article Q309694. You can find Knowledge Base articles on the MSDN Library media or at http://support.microsoft.com/support/.
An application compiled with initialAppDomain should never be used by an application using ASP.NET. Upgrade to a newer runtime to do ASP.NET work with C++.
/bigobj increases the number of sections that an object file can contain.
/bigobj
Remarks
By default, an object file can hold up to 65,536 (2^16) addressable sections. /bigobj increases that address capacity to 4,294,967,296 (2^32).
Most modules will never generate an .obj file that contains more than 65,536 sections. However, machine generated code, or code that makes heavy use of template libraries may require .obj files that can hold more sections.
An .obj file produced with /bigobj can only be consumed by a linker that shipped in Visual C++ 2005 (or later). Linkers that shipped prior to Visual C++ 2005 cannot read .obj files that were produced with /bigobj.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Command Line property page.
4. Type the compiler option in the Additional Options box.
Remarks
By default, an object file can hold up to 65,536 (2^16) addressable sections. /bigobj increases that address capacity to 4,294,967,296 (2^32).
Most modules will never generate an .obj file that contains more than 65,536 sections. However, machine generated code, or code that makes heavy use of template libraries may require .obj files that can hold more sections.
An .obj file produced with /bigobj can only be consumed by a linker that shipped in Visual C++ 2005 (or later). Linkers that shipped prior to Visual C++ 2005 cannot read .obj files that were produced with /bigobj.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Click the C/C++ folder.
3. Click the Command Line property page.
4. Type the compiler option in the Additional Options box.
/analyze (Enterprise Code Analysis)
Enable code analysis.
/analyze[:WX-]
Remarks
Specifying /analyze:WX- means code analysis warnings will not be treated as errors when compiling with /WX. See /w, /Wn, /WX, /Wall, /wln, /wdn, /wen, /won (Warning Level) for more information.
/analyze is only available in Enterprise (team development) versions for x86 compilers.
For more information on code analysis, see Code Analysis for C/C++ Overview and C/C++ Code Analysis Warnings.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Expand the Configuration Properties node.
3. Expand the Code Analysis node.
4. Select the General property page.
5. Modify one or more of the Code Analysis properties.
/analyze[:WX-]
Remarks
Specifying /analyze:WX- means code analysis warnings will not be treated as errors when compiling with /WX. See /w, /Wn, /WX, /Wall, /wln, /wdn, /wen, /won (Warning Level) for more information.
/analyze is only available in Enterprise (team development) versions for x86 compilers.
For more information on code analysis, see Code Analysis for C/C++ Overview and C/C++ Code Analysis Warnings.
To set this compiler option in the Visual Studio development environment
1. Open the project's Property Pages dialog box. For details, see How to: Open Project Property Pages.
2. Expand the Configuration Properties node.
3. Expand the Code Analysis node.
4. Select the General property page.
5. Modify one or more of the Code Analysis properties.
Compiler Options
cl.exe is a tool that controls the Microsoft C and C++ compilers and linker. cl.exe can only be run on Windows 2000, Windows XP and Windows Server 2003 operating systems.
The compilers produce Common Object File Format (COFF) object (.obj) files. The linker produces executable (.exe) files or dynamic-link libraries (DLLs).
Note that all compiler options are case sensitive.
To compile without linking, use /c.
Finding an Option
To find a particular compiler option, see one of the following lists:
Compiler Options Listed Alphabetically
Compiler Options Listed by Category
Specifying Options
For information on specifying options, see:
Setting Compiler Options
Fast Compilation
CL Invokes the Linker
Related Build Tools
Use NMAKE to build your output file.
Use BSCMAKE to support class browsing.
Linker options also affect how your program is built.
The compilers produce Common Object File Format (COFF) object (.obj) files. The linker produces executable (.exe) files or dynamic-link libraries (DLLs).
Note that all compiler options are case sensitive.
To compile without linking, use /c.
Finding an Option
To find a particular compiler option, see one of the following lists:
Compiler Options Listed Alphabetically
Compiler Options Listed by Category
Specifying Options
For information on specifying options, see:
Setting Compiler Options
Fast Compilation
CL Invokes the Linker
Related Build Tools
Use NMAKE to build your output file.
Use BSCMAKE to support class browsing.
Linker options also affect how your program is built.
Breaking Changes in the Visual C++ 2005 Compiler
This topic discusses the behavior changes in Visual C++ 2005 that can cause code that worked in a previous release to either not compile, or to behave differently at run time.
Pointer-to-members now require qualified name and &
Code written for previous versions of the compiler that just used the method name will now give Compiler Error C3867 or Compiler Warning C4867. This diagnostic is required by Standard C++. Now, to create a pointer to a member function, the address of operator (&) must be used with the fully qualified name of the method. Not having to use the & operator and the fully qualified name of the method can lead to logic bugs in code due missing parentheses in function calls. Using the function's name without an argument list results in a function pointer which is convertible to several types. This code would have compiled, leading to unexpected behavior at runtime.
Class must be accessible to a friend declaration
Visual C++ compilers prior to Visual C++ 2005 allowed a friend declaration to a class that was not accessible in the scope of the class containing the declaration. Now, the compiler will give Compiler Error C2248. To resolve this error, change the accessibility of the class specified in the friend declaration. This change was made to comply with the C++ standard.
__int asm 3 now compiles to native
When compiled with /clr, __asm int 3 did not cause native code to be generated; the compiler translated the instruction to a CLR break instruction. In Visual C++ 2005, __asm int 3 now results in native code generation for the function. If you want a function to cause a break point in your code and if you want that function compiled to MSIL, use __debugbreak. For more information, see __asm and /clr (Common Language Runtime Compilation). This change was made to be more deterministic about when to generate native code versus managed code; inline assembly code should generate native code.
Explicit specialization not allowed as a copy constructor/copy assignment operator
Code that depends on an explicit template specialization for a copy constructor or copy assignment operator will now get Compiler Error C2299. Standard C++ prohibits this. This change was made for conformance reasons, to make code more portable.
Unspecialized class template can't be used as a template argument in a base class list
Using an unspecialized template class name in the base class list for a class definition will result in Compiler Error C3203. It is illegal to use an unspecialized template class name as a template parameter in a base class list. Explicitly add the template type parameters to the template class name when using it as a template parameter in a base class list. This change was made for conformance reasons, to make code more portable.
A using declaration of nested type no longer allowed
Code that has a using declaration to a nested type will now generate Compiler Error C2885. To resolve fully qualify references to nested types, put the type in a namespace, or create a typedef. This change was made for conformance reasons, to make code more portable.
Compiler does not allow const_cast to down cast under /clr:oldSyntax
Prior to Visual C++ 2005 the Visual C++ compiler allowed the const_cast Operator to down cast when compiling source code that uses Managed Extensions for C++ syntax. Performing a down cast with const_cast now results in Compiler Error C2440. To resolve, use the correct cast operator (for more information, see Casting Operators). This change was made for conformance reasons.
Compiler disallows forward declaration of a managed enum
Prior to Visual C++ 2005 the Visual C++ compiler allowed forward declarations of managed enums. Now, declaring and not defining a managed enum when compiling with any form of /clr will result in Compiler Error C2599. To resolve, always define managed enums at declaration. This change was made because forward declarations of managed enums were not always guaranteed to work correctly: the compiler cannot correctly identify the underlying type of the enum. Also the C++ Standard does not allow enum declarations.
/YX compiler option is removed
/YX generated automatic pre-compiled headers support. It was used by default from the development environment. If you remove /YX from your build configurations and replace it with nothing, it can result in faster builds. In addition to the possibility of unexpected behavior with /YX, it is preferable to use /Yc (Create Precompiled Header File) and /Yu (Use Precompiled Header File), which give you more control on how precompiled headers are used.
/Oa and /Ow compiler options are removed
/Ow and /Oa compiler options have been removed but will be silently ignored. Use the noalias or restrict __declspec modifiers to specify how the compiler does aliasing.
/Op compiler option is removed
/Op compiler option had been removed. Use /fp (Specify Floating-Point Behavior) instead.
/ML and /MLd compiler options have been removed
Visual C++ no longer supports single-threaded, statically linked CRT library support. Use /MT and /MTd instead. See C Run-Time Libraries for more information.
/G3, /G4, /G5, /G6, /G7, and /GB compiler options have been removed
The compiler now uses a blended model that attempts to create the best output file for all architectures.
/Gf has been removed
Use /GF (Eliminate Duplicate Strings) instead. /GF puts pooled strings into a read-only section, which is safer than the writeable section, where /Gf added them.
/clr is not compatible with /MT
There is no support in the C Runtime Library to statically link to a managed application. All managed applications have to be dynamically linked (/MD). For more information on restrictions on using /clr, see /clr Restrictions.
/GS is now on by default
Buffer overflow checking is now on by default. You can turn buffer overrun checking off with /GS-. See /GS (Buffer Security Check) for more information.
/Zc:wchar_t now on by default
This is Standard C++ behavior; a wchar_t variable will default to the built in type instead of a short unsigned integer. This change will break binary compatibility when client code is linked with libraries that were compiled without /Zc:wchar_t (LNK2019). In that case, use /Zc:wchar_t- to revert to the old, non-standard behavior. This change was introduced to create conformant code by default.For more information
/Zc:forScope now on by default
This is Standard C++ behavior; code that depends on the use of a variable declared in a for loop after the for loop scope has ended will now fail to compile. Use /Zc:forScope- to revert to the old, non-standard behavior. This change was introduced to create conformant code by default.For more information
Enforce parameter checking for Visual C++ attributes
Code that passes named attributes to the attribute constructor in quotes when
will now give Compiler Error C2065 or Compiler Warning (level 1) C4581. Previously all compiler attributes were parsed as strings, and if needed, the compiler inserted the missing quotes. Attribute support was enhanced by adding parameter checking validation. This will prevent unexpected behavior due to incorrect arguments to an attribute constructor.
Compiler now requires same template specification for multiple declarations of the same type.
If you have a forward declaration of a type so that you can create friends to that type, for example, the template specification of the type must be the same on all declarations for the type. Otherwise, the compiler will issue Compiler Error C2990.
uuid attribute can no longer target managed types
The uuid (C++ Attributes) attribute was allowed on a user-defined attribute using Managed Extensions for C++, but will now generate Compiler Error C3451. Use GuidAttribute instead.
Syntax change for passing managed arrays to custom attributes
The type of the array is no longer deduced from the aggregate initialization list. The compiler now requires you to specify the type of the array as well as the initializer list. The old syntax will now result in Compiler Error C3104. This change was required because the compiler could not always correctly deduce the array type from the aggregate initialization list.
Compiler will not inject int as the default type in declarations
Code that is missing the type in a declaration will no longer default to type int the compiler will generate Compiler Warning C4430 or Compiler Warning (level 4) C4431. Standard C++ does not support a default int and this change will ensure that you get the type you really want.
dynamic_cast has enhanced conformance to the C++ standard.
The C runtime library now does a dynamic_cast runtime check to ensure the compile-time type of the expression being cast refers to a public base class sub-object of either the cast target type (for down-cast) or most-derived object type (for cross-cast). For more information, see Breaking Changes in dynamic_cast.
An rvalue cannot be bound to a non-const reference.
An rvalue cannot be bound to a non-const reference. In previous versions of Visual C++, it was possible to bind an rvalue to a non-const reference in a direct initialization. This code now generates Compiler Warning (level 1) C4350.
Value types no longer have a default constructor emitted, this can cause type initializers to run at different points
Prior to Visual C++ 2005 static constructors (type initializers) in value types were run when an instance of the value type was created. To ensure that static constructors are run, access a static data member or (/clr:oldSyntax only) define an instance constructor. Not providing a default constructor for value types was done because the common language runtime does not guarantee it will always call a default constructor. Also, not providing a default constructor for value types improves performance.
Boxed value types are now read only in verifiable (/clr:safe) contexts.
The common language runtime no longer allows modifying a boxed value type when compiling a verifiable assembly. The compiler now gives Compiler Warning C4972 when this is detected.
C4792 is only given if you change the value of the underlying value object via boxed value object. The error will not occur if you change a copy of the value object (for example, changing a boxed object)
Native types are private by default outside the assembly
Native types now will not be visible outside the assembly by default. For more information on type visibility outside the assembly, see Type Visibility. This change was primarily driven by the needs of developers using other, case-insensitive languages, when referencing metadata authored in Visual C++.
/clr now accepts new CLR syntax for Visual C++
Prior to Visual C++ 2005, /clr compiled Managed Extensions for C++ syntax. /clr now compiles the new CLR syntax and ./clr:oldSyntax compiles Managed Extensions for C++ syntax. For more information on /clr, see /clr (Common Language Runtime Compilation). For more information on the new syntax, see New C++ Language Features.
/clr no longer compiles C source code files
Prior to Visual C++ 2005, you could compile C source code files with /clr, however this will now result in Command-Line Error D8045. To resolve, change the file extension to .cpp or .cxx, or compile with /TP or /Tp. See /Tc, /Tp, /TC, /TP (Specify Source File Type) for more information.
MSIL changes when testing for equality&
Pointer-to-members now require qualified name and &
Code written for previous versions of the compiler that just used the method name will now give Compiler Error C3867 or Compiler Warning C4867. This diagnostic is required by Standard C++. Now, to create a pointer to a member function, the address of operator (&) must be used with the fully qualified name of the method. Not having to use the & operator and the fully qualified name of the method can lead to logic bugs in code due missing parentheses in function calls. Using the function's name without an argument list results in a function pointer which is convertible to several types. This code would have compiled, leading to unexpected behavior at runtime.
Class must be accessible to a friend declaration
Visual C++ compilers prior to Visual C++ 2005 allowed a friend declaration to a class that was not accessible in the scope of the class containing the declaration. Now, the compiler will give Compiler Error C2248. To resolve this error, change the accessibility of the class specified in the friend declaration. This change was made to comply with the C++ standard.
__int asm 3 now compiles to native
When compiled with /clr, __asm int 3 did not cause native code to be generated; the compiler translated the instruction to a CLR break instruction. In Visual C++ 2005, __asm int 3 now results in native code generation for the function. If you want a function to cause a break point in your code and if you want that function compiled to MSIL, use __debugbreak. For more information, see __asm and /clr (Common Language Runtime Compilation). This change was made to be more deterministic about when to generate native code versus managed code; inline assembly code should generate native code.
Explicit specialization not allowed as a copy constructor/copy assignment operator
Code that depends on an explicit template specialization for a copy constructor or copy assignment operator will now get Compiler Error C2299. Standard C++ prohibits this. This change was made for conformance reasons, to make code more portable.
Unspecialized class template can't be used as a template argument in a base class list
Using an unspecialized template class name in the base class list for a class definition will result in Compiler Error C3203. It is illegal to use an unspecialized template class name as a template parameter in a base class list. Explicitly add the template type parameters to the template class name when using it as a template parameter in a base class list. This change was made for conformance reasons, to make code more portable.
A using declaration of nested type no longer allowed
Code that has a using declaration to a nested type will now generate Compiler Error C2885. To resolve fully qualify references to nested types, put the type in a namespace, or create a typedef. This change was made for conformance reasons, to make code more portable.
Compiler does not allow const_cast to down cast under /clr:oldSyntax
Prior to Visual C++ 2005 the Visual C++ compiler allowed the const_cast Operator to down cast when compiling source code that uses Managed Extensions for C++ syntax. Performing a down cast with const_cast now results in Compiler Error C2440. To resolve, use the correct cast operator (for more information, see Casting Operators). This change was made for conformance reasons.
Compiler disallows forward declaration of a managed enum
Prior to Visual C++ 2005 the Visual C++ compiler allowed forward declarations of managed enums. Now, declaring and not defining a managed enum when compiling with any form of /clr will result in Compiler Error C2599. To resolve, always define managed enums at declaration. This change was made because forward declarations of managed enums were not always guaranteed to work correctly: the compiler cannot correctly identify the underlying type of the enum. Also the C++ Standard does not allow enum declarations.
/YX compiler option is removed
/YX generated automatic pre-compiled headers support. It was used by default from the development environment. If you remove /YX from your build configurations and replace it with nothing, it can result in faster builds. In addition to the possibility of unexpected behavior with /YX, it is preferable to use /Yc (Create Precompiled Header File) and /Yu (Use Precompiled Header File), which give you more control on how precompiled headers are used.
/Oa and /Ow compiler options are removed
/Ow and /Oa compiler options have been removed but will be silently ignored. Use the noalias or restrict __declspec modifiers to specify how the compiler does aliasing.
/Op compiler option is removed
/Op compiler option had been removed. Use /fp (Specify Floating-Point Behavior) instead.
/ML and /MLd compiler options have been removed
Visual C++ no longer supports single-threaded, statically linked CRT library support. Use /MT and /MTd instead. See C Run-Time Libraries for more information.
/G3, /G4, /G5, /G6, /G7, and /GB compiler options have been removed
The compiler now uses a blended model that attempts to create the best output file for all architectures.
/Gf has been removed
Use /GF (Eliminate Duplicate Strings) instead. /GF puts pooled strings into a read-only section, which is safer than the writeable section, where /Gf added them.
/clr is not compatible with /MT
There is no support in the C Runtime Library to statically link to a managed application. All managed applications have to be dynamically linked (/MD). For more information on restrictions on using /clr, see /clr Restrictions.
/GS is now on by default
Buffer overflow checking is now on by default. You can turn buffer overrun checking off with /GS-. See /GS (Buffer Security Check) for more information.
/Zc:wchar_t now on by default
This is Standard C++ behavior; a wchar_t variable will default to the built in type instead of a short unsigned integer. This change will break binary compatibility when client code is linked with libraries that were compiled without /Zc:wchar_t (LNK2019). In that case, use /Zc:wchar_t- to revert to the old, non-standard behavior. This change was introduced to create conformant code by default.For more information
/Zc:forScope now on by default
This is Standard C++ behavior; code that depends on the use of a variable declared in a for loop after the for loop scope has ended will now fail to compile. Use /Zc:forScope- to revert to the old, non-standard behavior. This change was introduced to create conformant code by default.For more information
Enforce parameter checking for Visual C++ attributes
Code that passes named attributes to the attribute constructor in quotes when
will now give Compiler Error C2065 or Compiler Warning (level 1) C4581. Previously all compiler attributes were parsed as strings, and if needed, the compiler inserted the missing quotes. Attribute support was enhanced by adding parameter checking validation. This will prevent unexpected behavior due to incorrect arguments to an attribute constructor.
Compiler now requires same template specification for multiple declarations of the same type.
If you have a forward declaration of a type so that you can create friends to that type, for example, the template specification of the type must be the same on all declarations for the type. Otherwise, the compiler will issue Compiler Error C2990.
uuid attribute can no longer target managed types
The uuid (C++ Attributes) attribute was allowed on a user-defined attribute using Managed Extensions for C++, but will now generate Compiler Error C3451. Use GuidAttribute instead.
Syntax change for passing managed arrays to custom attributes
The type of the array is no longer deduced from the aggregate initialization list. The compiler now requires you to specify the type of the array as well as the initializer list. The old syntax will now result in Compiler Error C3104. This change was required because the compiler could not always correctly deduce the array type from the aggregate initialization list.
Compiler will not inject int as the default type in declarations
Code that is missing the type in a declaration will no longer default to type int the compiler will generate Compiler Warning C4430 or Compiler Warning (level 4) C4431. Standard C++ does not support a default int and this change will ensure that you get the type you really want.
dynamic_cast has enhanced conformance to the C++ standard.
The C runtime library now does a dynamic_cast runtime check to ensure the compile-time type of the expression being cast refers to a public base class sub-object of either the cast target type (for down-cast) or most-derived object type (for cross-cast). For more information, see Breaking Changes in dynamic_cast.
An rvalue cannot be bound to a non-const reference.
An rvalue cannot be bound to a non-const reference. In previous versions of Visual C++, it was possible to bind an rvalue to a non-const reference in a direct initialization. This code now generates Compiler Warning (level 1) C4350.
Value types no longer have a default constructor emitted, this can cause type initializers to run at different points
Prior to Visual C++ 2005 static constructors (type initializers) in value types were run when an instance of the value type was created. To ensure that static constructors are run, access a static data member or (/clr:oldSyntax only) define an instance constructor. Not providing a default constructor for value types was done because the common language runtime does not guarantee it will always call a default constructor. Also, not providing a default constructor for value types improves performance.
Boxed value types are now read only in verifiable (/clr:safe) contexts.
The common language runtime no longer allows modifying a boxed value type when compiling a verifiable assembly. The compiler now gives Compiler Warning C4972 when this is detected.
C4792 is only given if you change the value of the underlying value object via boxed value object. The error will not occur if you change a copy of the value object (for example, changing a boxed object)
Native types are private by default outside the assembly
Native types now will not be visible outside the assembly by default. For more information on type visibility outside the assembly, see Type Visibility. This change was primarily driven by the needs of developers using other, case-insensitive languages, when referencing metadata authored in Visual C++.
/clr now accepts new CLR syntax for Visual C++
Prior to Visual C++ 2005, /clr compiled Managed Extensions for C++ syntax. /clr now compiles the new CLR syntax and ./clr:oldSyntax compiles Managed Extensions for C++ syntax. For more information on /clr, see /clr (Common Language Runtime Compilation). For more information on the new syntax, see New C++ Language Features.
/clr no longer compiles C source code files
Prior to Visual C++ 2005, you could compile C source code files with /clr, however this will now result in Command-Line Error D8045. To resolve, change the file extension to .cpp or .cxx, or compile with /TP or /Tp. See /Tc, /Tp, /TC, /TP (Specify Source File Type) for more information.
MSIL changes when testing for equality&
Using the Visual Studio IDE
The Visual Studio Integrated Development Environment (IDE) offers a set of tools that help you write and edit the code for your programs, as well as detect and correct errors in your programs.
In this topic, you create a new standard C++ program and test its functionality using features available in Visual Studio for the C++ developer.
This walkthrough covers the following:
Working with Projects and Solutions
Using Solution Explorer
Adding a Source File
Fixing Compilation Errors
Testing a Program
Debugging a Program
Working with Projects and Solutions
Visual Studio organizes your work in projects and solutions. A solution can contain more than one project, such as a DLL and an executable that references that DLL. For more information.
The first step in writing a C++ program with Visual Studio is to choose the type of project. For each project type, Visual Studio sets compiler settings and generates starter code for you.
To create a new project
1. On the File menu, point to New, and then click Project….
2. In the Project Types area, click Win32, then in the Visual Studio installed templates pane, click Win32 Console Application.
3. Type game as the project name.
When you create a new project, Visual Studio places the project in a solution. Accept the default name for the solution, which by default is the same name as the project.
You can accept the default location, type in a different location, or browse to a directory where you want to save the project.
4. From the Overview page of the Win32 Application Wizard dialog, press Next.
5. Select the Empty Project setting and click Finish.
You now have a project with no source code files.
Using Solution Explorer
Solution Explorer allows you to work with files and other resources in your solution.
In this step, you add a class to the project and Visual Studio adds the .h and .cpp files to your project. You then add a new source code file to the project for the main program that tests the class.
To add a class to a project
1. If the Solution Explorer window is not visible, on the View menu click Solution Explorer.
2. Right-click on the Header Files folder in Solution Explorer and point to Add, then click Class.
In the Visual C++ category, click C++ (or Generic if you are using Visual C++ Express Edition) and click C++ Class in the Visual Studio installed templates area. Click Add.
3. In the Generic C++ Class Wizard, type Cardgame as the Class name and accept the default file names, then click Finish.
4. Make these changes to the Cardgame.h file displayed in the editing area:
Add two private data members after the opening brace of the class definition:
int players;
static int totalparticipants;
Add a public constructor prototype that takes one parameter of type int:
Cardgame(int p);
Delete the default constructor generated for you, since you won't need it:
Cardgame(void);
5. The Cardgame.h file should look like this after your changes
// Cardgame.h
#pragma once
class Cardgame {
int players;
static int totalparticipants;
public:
Cardgame(int p);
~Cardgame(void);
};
6. Double-click on Cardgame.cpp in the Source Files folder to open it for editing.
7. Add the code for the constructor that takes one int argument:
Cardgame::Cardgame(int p)
{
players = p;
totalparticipants += p;
}
When you begin typing pl or to, you can press Ctrl-Spacebar and auto-completion will finish typing players or totalparticipants for you.
8. Delete the default constructor that was generated for you:
Cardgame::Cardgame(void);
9. The Cardgame.cpp file should look like this after your changes:
// Cardgame.cpp
#include "Cardgame.h"
Cardgame::Cardgame(int p)
{
players = p;
totalparticipants += p;
}
Cardgame::~Cardgame(void)
{
}
In this topic, you create a new standard C++ program and test its functionality using features available in Visual Studio for the C++ developer.
This walkthrough covers the following:
Working with Projects and Solutions
Using Solution Explorer
Adding a Source File
Fixing Compilation Errors
Testing a Program
Debugging a Program
Working with Projects and Solutions
Visual Studio organizes your work in projects and solutions. A solution can contain more than one project, such as a DLL and an executable that references that DLL. For more information.
The first step in writing a C++ program with Visual Studio is to choose the type of project. For each project type, Visual Studio sets compiler settings and generates starter code for you.
To create a new project
1. On the File menu, point to New, and then click Project….
2. In the Project Types area, click Win32, then in the Visual Studio installed templates pane, click Win32 Console Application.
3. Type game as the project name.
When you create a new project, Visual Studio places the project in a solution. Accept the default name for the solution, which by default is the same name as the project.
You can accept the default location, type in a different location, or browse to a directory where you want to save the project.
4. From the Overview page of the Win32 Application Wizard dialog, press Next.
5. Select the Empty Project setting and click Finish.
You now have a project with no source code files.
Using Solution Explorer
Solution Explorer allows you to work with files and other resources in your solution.
In this step, you add a class to the project and Visual Studio adds the .h and .cpp files to your project. You then add a new source code file to the project for the main program that tests the class.
To add a class to a project
1. If the Solution Explorer window is not visible, on the View menu click Solution Explorer.
2. Right-click on the Header Files folder in Solution Explorer and point to Add, then click Class.
In the Visual C++ category, click C++ (or Generic if you are using Visual C++ Express Edition) and click C++ Class in the Visual Studio installed templates area. Click Add.
3. In the Generic C++ Class Wizard, type Cardgame as the Class name and accept the default file names, then click Finish.
4. Make these changes to the Cardgame.h file displayed in the editing area:
Add two private data members after the opening brace of the class definition:
int players;
static int totalparticipants;
Add a public constructor prototype that takes one parameter of type int:
Cardgame(int p);
Delete the default constructor generated for you, since you won't need it:
Cardgame(void);
5. The Cardgame.h file should look like this after your changes
// Cardgame.h
#pragma once
class Cardgame {
int players;
static int totalparticipants;
public:
Cardgame(int p);
~Cardgame(void);
};
6. Double-click on Cardgame.cpp in the Source Files folder to open it for editing.
7. Add the code for the constructor that takes one int argument:
Cardgame::Cardgame(int p)
{
players = p;
totalparticipants += p;
}
When you begin typing pl or to, you can press Ctrl-Spacebar and auto-completion will finish typing players or totalparticipants for you.
8. Delete the default constructor that was generated for you:
Cardgame::Cardgame(void);
9. The Cardgame.cpp file should look like this after your changes:
// Cardgame.cpp
#include "Cardgame.h"
Cardgame::Cardgame(int p)
{
players = p;
totalparticipants += p;
}
Cardgame::~Cardgame(void)
{
}
Standard C++ Library Reference
A C++ program can call on a large number of functions from this conforming implementation of the Standard C++ Library. These functions perform essential services such as input and output and provide efficient implementations of frequently used operations.
For more information about Visual C++ run-time libraries, see C Run-Time Libraries.
In This SectionBreaking Changes in the Standard C++ LibraryThis section describes the breaking changes in Visual C++ 2005.
Standard C++ Library OverviewProvides an overview of the Microsoft implementation of the Standard C++ Library.
iostream ProgrammingProvides an overview of iostream programming.
Standard C++ Library Header FilesProvides links to reference topics discussing the Standard C++ Library header files.
Standard Template Library SamplesProvides links to sample code showing how to use the Standard Template Library.
Related SectionsStandard C++ Library ChangesDescribes changes to the Standard C++ Library implementation.
Visual C++ ReferenceProvides links to topics describing the C and C++ language references, the libraries provided with Visual C++, the Visual C++ Extensibility Object Model, and the Microsoft Macro Assembler (MASM).
Visual C++ SamplesProvides links to sample code showing
For more information about Visual C++ run-time libraries, see C Run-Time Libraries.
In This SectionBreaking Changes in the Standard C++ LibraryThis section describes the breaking changes in Visual C++ 2005.
Standard C++ Library OverviewProvides an overview of the Microsoft implementation of the Standard C++ Library.
iostream ProgrammingProvides an overview of iostream programming.
Standard C++ Library Header FilesProvides links to reference topics discussing the Standard C++ Library header files.
Standard Template Library SamplesProvides links to sample code showing how to use the Standard Template Library.
Related SectionsStandard C++ Library ChangesDescribes changes to the Standard C++ Library implementation.
Visual C++ ReferenceProvides links to topics describing the C and C++ language references, the libraries provided with Visual C++, the Visual C++ Extensibility Object Model, and the Microsoft Macro Assembler (MASM).
Visual C++ SamplesProvides links to sample code showing
Run-Time Library Behavior
The C/C++ run-time library code performs the DLL startup sequence, eliminating the need to link with a separate module as was necessary in Windows 3.x. Included in the C/C++ run-time library code is the DLL entry-point function called _DllMainCRTStartup. The _DllMainCRTStartup function does several things, including calling _CRT_INIT, which initializes the C/C++ run-time library and invokes C++ constructors on static, non-local variables. Without this function, the run-time library would be left in an uninitialized state. _CRT_INIT is available for both a statically linked CRT or linking to the CRT DLL Msvcrt.dll, from a user DLL.
While it is possible to specify another entry-point function using the /ENTRY: linker option, it is not recommended because your entry-point function would have to duplicate everything that _DllMainCRTStartup does. When building DLLs in Visual C++, _DllMainCRTStartup is linked in automatically and you do not need to specify an entry-point function using the /ENTRY: linker option.
In addition to initializing the C run-time library, _DllMainCRTStartup calls a function called DllMain. Depending on the kind of DLL you are building, Visual C++ provides DllMain for you and it gets linked in so that _DllMainCRTStartup always has something to call. In this way, if you do not need to initialize your DLL, there is nothing special you have to do when building your DLL. If you need to initialize your DLL, where you add your code depends on the kind of DLL you are writing. For more information, see Initializing a DLL.
The C/C++ run-time library code calls constructors and destructors on static, non-local variables. For example, in the following DLL source code, Equus and Sugar are two static, non-local objects of class CHorse, defined in Horses.h. There is no function in source code that contains calls to a constructor function for CHorse or to the destructor function because these objects are defined outside of any function. Therefore, calls to these constructors and destructors must be performed by the run-time code. The run-time library code for applications also performs this function.
#include "horses.h"
CHorse Equus( ARABIAN, MALE );CHorse Sugar( THOROUGHBRED, FEMALE );
BOOL WINAPI DllMain (HANDLE hInst, ULONG ul_reason_for_call,LPVOID lpReserved)...
Each time a new process attempts to use the DLL, the operating system creates a separate copy of the DLL's data: this is called process attach. The run-time library code for the DLL calls the constructors for all of the global objects, if any, and then calls the DllMain function with process attach selected. The opposite situation is process detach: the run-time library code calls DllMain with process detach selected and then calls a list of termination functions, including atexit functions, destructors for the global objects, and destructors for the static objects. Note that the order of events in process attach is the reverse of that in process detach.
The run-time library code is also called during thread attach and thread detach, but the run-time code does no initialization or termination on its own.
While it is possible to specify another entry-point function using the /ENTRY: linker option, it is not recommended because your entry-point function would have to duplicate everything that _DllMainCRTStartup does. When building DLLs in Visual C++, _DllMainCRTStartup is linked in automatically and you do not need to specify an entry-point function using the /ENTRY: linker option.
In addition to initializing the C run-time library, _DllMainCRTStartup calls a function called DllMain. Depending on the kind of DLL you are building, Visual C++ provides DllMain for you and it gets linked in so that _DllMainCRTStartup always has something to call. In this way, if you do not need to initialize your DLL, there is nothing special you have to do when building your DLL. If you need to initialize your DLL, where you add your code depends on the kind of DLL you are writing. For more information, see Initializing a DLL.
The C/C++ run-time library code calls constructors and destructors on static, non-local variables. For example, in the following DLL source code, Equus and Sugar are two static, non-local objects of class CHorse, defined in Horses.h. There is no function in source code that contains calls to a constructor function for CHorse or to the destructor function because these objects are defined outside of any function. Therefore, calls to these constructors and destructors must be performed by the run-time code. The run-time library code for applications also performs this function.
#include "horses.h"
CHorse Equus( ARABIAN, MALE );CHorse Sugar( THOROUGHBRED, FEMALE );
BOOL WINAPI DllMain (HANDLE hInst, ULONG ul_reason_for_call,LPVOID lpReserved)...
Each time a new process attempts to use the DLL, the operating system creates a separate copy of the DLL's data: this is called process attach. The run-time library code for the DLL calls the constructors for all of the global objects, if any, and then calls the DllMain function with process attach selected. The opposite situation is process detach: the run-time library code calls DllMain with process detach selected and then calls a list of termination functions, including atexit functions, destructors for the global objects, and destructors for the static objects. Note that the order of events in process attach is the reverse of that in process detach.
The run-time library code is also called during thread attach and thread detach, but the run-time code does no initialization or termination on its own.
Run-Time Library Reference
The Microsoft run-time library provides routines for programming for the Microsoft Windows operating system. These routines automate many common programming tasks that are not provided by the C and C++ languages.
Sample programs are included in the individual reference topics for most routines in the library.
In This SectionC Run-Time LibrariesDiscusses the .lib files that comprise the C run-time libraries.
Run-Time Routines by CategoryProvides links to the run-time library by category.
Global Variables and Standard TypesProvides links to the global variables and standard types provided by the run-time library.
Global ConstantsProvides links to the global constants defined by the run-time library.
Alphabetical Function ReferenceProvides a table of contents entry point into an alphabetical listing of all C run-time library functions.
Generic-Text MappingsProvides links to the generic-text mappings defined in Tchar.h.
Language and Country/Region StringsDescribes how to use the setlocale function to set the language and Country/Region strings.
Related SectionsDebug RoutinesProvides links to the debug versions of the run-time library routines.
Run-Time Error CheckingProvides links to functions that support run-time error checks.
Run-Time Library BehaviorDiscusses the entry point into the CRT DLL.
Visual C++ LibrariesProvides links to the various libraries provided with Visual C++, including ATL, MFC, OLE DB Templates, the C run-time library, and the Standard C++ Library.
DebuggingProvides links to using the Visual Studio debugger to correct logic errors in your application or stored procedures.
run time library behavior
Sample programs are included in the individual reference topics for most routines in the library.
In This SectionC Run-Time LibrariesDiscusses the .lib files that comprise the C run-time libraries.
Run-Time Routines by CategoryProvides links to the run-time library by category.
Global Variables and Standard TypesProvides links to the global variables and standard types provided by the run-time library.
Global ConstantsProvides links to the global constants defined by the run-time library.
Alphabetical Function ReferenceProvides a table of contents entry point into an alphabetical listing of all C run-time library functions.
Generic-Text MappingsProvides links to the generic-text mappings defined in Tchar.h.
Language and Country/Region StringsDescribes how to use the setlocale function to set the language and Country/Region strings.
Related SectionsDebug RoutinesProvides links to the debug versions of the run-time library routines.
Run-Time Error CheckingProvides links to functions that support run-time error checks.
Run-Time Library BehaviorDiscusses the entry point into the CRT DLL.
Visual C++ LibrariesProvides links to the various libraries provided with Visual C++, including ATL, MFC, OLE DB Templates, the C run-time library, and the Standard C++ Library.
DebuggingProvides links to using the Visual Studio debugger to correct logic errors in your application or stored procedures.
run time library behavior
Visual C++ Express Edition Reference
The following links take you to topics providing reference material for Visual C++.
In This SectionC/C++ LanguagesProvides links to the C language reference, the C++ language reference, and C and C++ preprocessor directives reference.
Run-Time Library ReferenceProvides reference material for the C Run-Time Library, a set of routines that automate many common programming tasks that are not provided by the C and C++ languages.
Standard C++ Library ReferenceProvides reference material for the Standard C++ Library implementation, a set of header files that provide functions to perform essential services such as input and output and provide efficient implementations of frequently used operations.
In This SectionC/C++ LanguagesProvides links to the C language reference, the C++ language reference, and C and C++ preprocessor directives reference.
Run-Time Library ReferenceProvides reference material for the C Run-Time Library, a set of routines that automate many common programming tasks that are not provided by the C and C++ languages.
Standard C++ Library ReferenceProvides reference material for the Standard C++ Library implementation, a set of header files that provide functions to perform essential services such as input and output and provide efficient implementations of frequently used operations.
Transaction (ODBC)
This topic applies to the MFC ODBC classes.
A transaction is a way to group, or batch, a series of updates to a data source so that all are committed at once or none are committed if you roll back the transaction. If you do not use a transaction, changes to the data source are committed automatically rather than being committed on demand.
Note Not all ODBC database drivers support transactions. Call the CanTransact member function of your CDatabase or CRecordset object to determine whether your driver supports transactions for a given database. Note that CanTransact does not tell you whether the data source provides full transaction support. You must also call CDatabase::GetCursorCommitBehavior and CDatabase::GetCursorRollbackBehavior after CommitTrans and Rollback to check the effect of the transaction on the open CRecordset object.
Calls to the AddNew and Edit member functions of a CRecordset object affect the data source immediately when you call Update. Delete calls also take effect immediately. In contrast, you can use a transaction consisting of multiple calls to AddNew, Edit, Update, and Delete, which are performed but not committed until you call CommitTrans explicitly. By establishing a transaction, you can execute a series of such calls while retaining the ability to roll them back. If a critical resource is unavailable or some other condition prevents the entire transaction from being completed, you can roll back the transaction instead of committing it. In that case, none of the changes belonging to the transaction affect the data source.
Note Currently, class CRecordset does not support updates to the data source if you have implemented bulk row fetching. This means you cannot make calls to AddNew, Edit, Delete, or Update. However, you can write you own functions to perform updates and then call those functions within a given transaction. For more information about bulk row fetching, see Recordset: Fetching Records in Bulk (ODBC).Note Besides affecting your recordset, transactions affect SQL statements that you execute directly as long as you use the ODBC HDBC associated with your CDatabase object or an ODBC HSTMT based on that HDBC.
Transactions are particularly useful when you have multiple records that must be updated simultaneously. In this case, you want to avoid a half-completed transaction, such as might happen if an exception was thrown before the last update was made. Grouping such updates into a transaction allows a recovery (rollback) from the changes and returns the records to the pretransaction state. For example, if a bank transfers money from account A to account B, both the withdrawal from A and the deposit to B must succeed to process the funds correctly or the whole transaction must fail.
In the database classes, you perform transactions through CDatabase objects. A CDatabase object represents a connection to a data source, and one or more recordsets associated with that CDatabase object operate on tables of the database through recordset member functions.
Note Only one level of transactions is supported. You cannot nest transactions nor can a transaction span multiple database objects.
The following topics provide more information about how transactions are performed:
Transaction: Performing a Transaction in a Recordset (ODBC)
Transaction: How Transactions Affect Updates (ODBC)
A transaction is a way to group, or batch, a series of updates to a data source so that all are committed at once or none are committed if you roll back the transaction. If you do not use a transaction, changes to the data source are committed automatically rather than being committed on demand.
Note Not all ODBC database drivers support transactions. Call the CanTransact member function of your CDatabase or CRecordset object to determine whether your driver supports transactions for a given database. Note that CanTransact does not tell you whether the data source provides full transaction support. You must also call CDatabase::GetCursorCommitBehavior and CDatabase::GetCursorRollbackBehavior after CommitTrans and Rollback to check the effect of the transaction on the open CRecordset object.
Calls to the AddNew and Edit member functions of a CRecordset object affect the data source immediately when you call Update. Delete calls also take effect immediately. In contrast, you can use a transaction consisting of multiple calls to AddNew, Edit, Update, and Delete, which are performed but not committed until you call CommitTrans explicitly. By establishing a transaction, you can execute a series of such calls while retaining the ability to roll them back. If a critical resource is unavailable or some other condition prevents the entire transaction from being completed, you can roll back the transaction instead of committing it. In that case, none of the changes belonging to the transaction affect the data source.
Note Currently, class CRecordset does not support updates to the data source if you have implemented bulk row fetching. This means you cannot make calls to AddNew, Edit, Delete, or Update. However, you can write you own functions to perform updates and then call those functions within a given transaction. For more information about bulk row fetching, see Recordset: Fetching Records in Bulk (ODBC).Note Besides affecting your recordset, transactions affect SQL statements that you execute directly as long as you use the ODBC HDBC associated with your CDatabase object or an ODBC HSTMT based on that HDBC.
Transactions are particularly useful when you have multiple records that must be updated simultaneously. In this case, you want to avoid a half-completed transaction, such as might happen if an exception was thrown before the last update was made. Grouping such updates into a transaction allows a recovery (rollback) from the changes and returns the records to the pretransaction state. For example, if a bank transfers money from account A to account B, both the withdrawal from A and the deposit to B must succeed to process the funds correctly or the whole transaction must fail.
In the database classes, you perform transactions through CDatabase objects. A CDatabase object represents a connection to a data source, and one or more recordsets associated with that CDatabase object operate on tables of the database through recordset member functions.
Note Only one level of transactions is supported. You cannot nest transactions nor can a transaction span multiple database objects.
The following topics provide more information about how transactions are performed:
Transaction: Performing a Transaction in a Recordset (ODBC)
Transaction: How Transactions Affect Updates (ODBC)
Supporting Transactions in OLE DB
A transaction is a way to group, or batch, a series of updates to a data source so that either all succeed and are committed at once or (if any one of them fails) none are committed and the entire transaction is rolled back. This process ensures the integrity of the result on the data source.
OLE DB supports transactions with the following three methods:
ITransactionLocal::StartTransaction
ITransaction::Commit
ITransaction::Abort
Relationship of Sessions and TransactionsA single data source object can create one or more session objects, each of which can be inside or outside the scope of a transaction at a given time.
When a session does not enter a transaction, all work done within that session on the data store is immediately committed on each method call. (This is sometimes referred to as autocommit mode or implicit mode.)
When a session enters a transaction, all work done within that session on the data store is part of that transaction and is committed or aborted as a single unit. (This is sometimes referred to as manual-commit mode.)
Transaction support is provider-specific. If the provider you are using supports transactions, a session object that supports ITransaction and ITransactionLocal can enter a simple (that is, non-nested) transaction. The OLE DB Templates class CSession supports these interfaces and is the recommended way to implement transaction support in Visual C++.
Starting and Ending the TransactionYou call the StartTransaction, Commit, and Abort methods in the rowset object in the consumer.
Calling ITransactionLocal::StartTransaction starts a new local transaction. When you start the transaction, any changes mandated by subsequent operations are not actually applied to the data store until you commit the transaction.
Calling ITransaction::Commit or ITransaction::Abort ends the transaction. Commit causes all changes within the scope of the transaction to be applied to the data store. Abort causes all changes within the scope of the transaction to be canceled and the data store is left in the state it had before the transaction started.
Nested TransactionsA nested transaction occurs when you start a new local transaction when an active transaction already exists on the session. The new transaction is started as a nested transaction below the current transaction. If the provider does not support nested transactions, calling StartTransaction when there is already an active transaction on the session returns XACT_E_XTIONEXISTS.
Distributed TransactionsA distributed transaction is a transaction that updates distributed data; that is, data on more than one networked computer system. If you want to support transactions over a distributed system, you should use the .NET Framework rather than the OLE DB transaction support.
For information about transactions in the Microsoft .NET Framework, see Processing Transactions in the Microsoft .NET Framework SDK.
OLE DB supports transactions with the following three methods:
ITransactionLocal::StartTransaction
ITransaction::Commit
ITransaction::Abort
Relationship of Sessions and TransactionsA single data source object can create one or more session objects, each of which can be inside or outside the scope of a transaction at a given time.
When a session does not enter a transaction, all work done within that session on the data store is immediately committed on each method call. (This is sometimes referred to as autocommit mode or implicit mode.)
When a session enters a transaction, all work done within that session on the data store is part of that transaction and is committed or aborted as a single unit. (This is sometimes referred to as manual-commit mode.)
Transaction support is provider-specific. If the provider you are using supports transactions, a session object that supports ITransaction and ITransactionLocal can enter a simple (that is, non-nested) transaction. The OLE DB Templates class CSession supports these interfaces and is the recommended way to implement transaction support in Visual C++.
Starting and Ending the TransactionYou call the StartTransaction, Commit, and Abort methods in the rowset object in the consumer.
Calling ITransactionLocal::StartTransaction starts a new local transaction. When you start the transaction, any changes mandated by subsequent operations are not actually applied to the data store until you commit the transaction.
Calling ITransaction::Commit or ITransaction::Abort ends the transaction. Commit causes all changes within the scope of the transaction to be applied to the data store. Abort causes all changes within the scope of the transaction to be canceled and the data store is left in the state it had before the transaction started.
Nested TransactionsA nested transaction occurs when you start a new local transaction when an active transaction already exists on the session. The new transaction is started as a nested transaction below the current transaction. If the provider does not support nested transactions, calling StartTransaction when there is already an active transaction on the session returns XACT_E_XTIONEXISTS.
Distributed TransactionsA distributed transaction is a transaction that updates distributed data; that is, data on more than one networked computer system. If you want to support transactions over a distributed system, you should use the .NET Framework rather than the OLE DB transaction support.
For information about transactions in the Microsoft .NET Framework, see Processing Transactions in the Microsoft .NET Framework SDK.
Transactions
The concept of a transaction was developed to handle cases in which the resulting state of the database depends on the total success of a series of operations. This could come about because successive operations might modify the results of previous operations. In such cases, if any one operation fails, the resulting state could be indeterminate.
To solve this problem, transactions group a series of operations in such a way that the integrity of the final result can be assured. Either all the operations must succeed and then be committed (written to the database) or the entire transaction fails. The cancellation of the transaction is called a rollback. Rollback allows a recovery from the changes and returns the database to the pretransaction state.
For example, in an automated banking transaction, if you transfer money from account A to account B, both the withdrawal from A and the deposit to B must succeed to process the funds correctly, or the whole transaction must fail.
A transaction must have ACID properties, which stand for the following:
Atomicity A transaction is an atomic unit of work and executes exactly once; either all the work is done or none of it is.
Consistency A transaction preserves the consistency of data, transforming one consistent state of data into another consistent state of data. Data bound by a transaction must be semantically preserved.
Isolation A transaction is a unit of isolation and each occurs separately and independently of concurrent transactions. A transaction should never see the intermediate stages of another transaction.
Durability A transaction is a unit of recovery. If a transaction succeeds, its updates persist, even if the system crashes or is shut down. If a transaction fails, the system remains in the state previous to committing the transaction.
You can support transactions in OLE DB (see Supporting Transactions in OLE DB) or ODBC (see Transaction (ODBC)).
A distributed transaction is a transaction that updates distributed data, that is, data on more than one networked computer system. If you want to support transactions over a distributed system, you should use the Microsoft .NET Framework rather than the OLE DB transaction support.
For information about transactions in the Microsoft .NET Framework, see Processing Transactions in the Microsoft .NET Framework SDK.
To solve this problem, transactions group a series of operations in such a way that the integrity of the final result can be assured. Either all the operations must succeed and then be committed (written to the database) or the entire transaction fails. The cancellation of the transaction is called a rollback. Rollback allows a recovery from the changes and returns the database to the pretransaction state.
For example, in an automated banking transaction, if you transfer money from account A to account B, both the withdrawal from A and the deposit to B must succeed to process the funds correctly, or the whole transaction must fail.
A transaction must have ACID properties, which stand for the following:
Atomicity A transaction is an atomic unit of work and executes exactly once; either all the work is done or none of it is.
Consistency A transaction preserves the consistency of data, transforming one consistent state of data into another consistent state of data. Data bound by a transaction must be semantically preserved.
Isolation A transaction is a unit of isolation and each occurs separately and independently of concurrent transactions. A transaction should never see the intermediate stages of another transaction.
Durability A transaction is a unit of recovery. If a transaction succeeds, its updates persist, even if the system crashes or is shut down. If a transaction fails, the system remains in the state previous to committing the transaction.
You can support transactions in OLE DB (see Supporting Transactions in OLE DB) or ODBC (see Transaction (ODBC)).
A distributed transaction is a transaction that updates distributed data, that is, data on more than one networked computer system. If you want to support transactions over a distributed system, you should use the Microsoft .NET Framework rather than the OLE DB transaction support.
For information about transactions in the Microsoft .NET Framework, see Processing Transactions in the Microsoft .NET Framework SDK.
Installing Database Support
When you run Setup for Visual C++ .NET, the following database components are installed automatically:
All the necessary ATL OLE DB components. For more information, see Installing ATL Database Support.
A set of ODBC drivers with the ODBC driver manager and the ODBC administrator program. For more information, see "ODBC Drivers Installed" and "ODBC SDK Components Installed" in Installing MFC Database Support.
Necessary components from the DAO software development kit (SDK). This includes Help files, which are not integrated with this documentation. However, if you work with DAO, you need to install a version of Jet compatible with your operating system. For more information, see "DAO SDK Components Installed" in Installing MFC Database Support.
As part of the baseline installation, Setup also installs Microsoft Data Access Components (MDAC), which are necessary to support data access programming in Visual C++ .NET.
Visual C++ .NET installs the MDAC 2.7 SDK. You should check the Microsoft Universal Data Access Web site at http://microsoft.com/data/ for updates to and news about the MDAC SDK.
If you are redistributing data access applications, you should also have the MDAC 2.7 redistribution program. The MDAC 2.7 SDK is designed for use with the MDAC 2.7 redistribution program (Mdac_typ.exe) included in the MDAC directory on the Visual Studio .NET Prerequisites CD-ROM. You can also download Mdac_typ.exe from the MDAC 2.7 SDK download link previously listed. For more information about redistributing components, see Redistributing Controls.
Record (Data Access)
A record is a collection of data about a single entity, such as an account or a customer, stored in a table (a row of the table). A record consists of a group of contiguous columns (sometimes called fields) that contain data of various types. A set of records selected from a data source — often called a result set in database terms — is called a recordset in MFC. For more information, see Recordset (ODBC).Schema (Data Access)
A database schema describes the current structure of the tables and database views in the database. In general, wizard-generated code assumes that the schema for the table or tables accessed by a recordset will not change, but the database classes can deal with some schema changes, such as adding, reordering, or deleting unbound columns. If a table changes, you must manually update the recordset for the table, then recompile your application.
You can also supplement the wizard-generated code to deal with a database whose schema is not entirely known at compile time. For more information
All the necessary ATL OLE DB components. For more information, see Installing ATL Database Support.
A set of ODBC drivers with the ODBC driver manager and the ODBC administrator program. For more information, see "ODBC Drivers Installed" and "ODBC SDK Components Installed" in Installing MFC Database Support.
Necessary components from the DAO software development kit (SDK). This includes Help files, which are not integrated with this documentation. However, if you work with DAO, you need to install a version of Jet compatible with your operating system. For more information, see "DAO SDK Components Installed" in Installing MFC Database Support.
As part of the baseline installation, Setup also installs Microsoft Data Access Components (MDAC), which are necessary to support data access programming in Visual C++ .NET.
Visual C++ .NET installs the MDAC 2.7 SDK. You should check the Microsoft Universal Data Access Web site at http://microsoft.com/data/ for updates to and news about the MDAC SDK.
If you are redistributing data access applications, you should also have the MDAC 2.7 redistribution program. The MDAC 2.7 SDK is designed for use with the MDAC 2.7 redistribution program (Mdac_typ.exe) included in the MDAC directory on the Visual Studio .NET Prerequisites CD-ROM. You can also download Mdac_typ.exe from the MDAC 2.7 SDK download link previously listed. For more information about redistributing components, see Redistributing Controls.
Record (Data Access)
A record is a collection of data about a single entity, such as an account or a customer, stored in a table (a row of the table). A record consists of a group of contiguous columns (sometimes called fields) that contain data of various types. A set of records selected from a data source — often called a result set in database terms — is called a recordset in MFC. For more information, see Recordset (ODBC).Schema (Data Access)
A database schema describes the current structure of the tables and database views in the database. In general, wizard-generated code assumes that the schema for the table or tables accessed by a recordset will not change, but the database classes can deal with some schema changes, such as adding, reordering, or deleting unbound columns. If a table changes, you must manually update the recordset for the table, then recompile your application.
You can also supplement the wizard-generated code to deal with a database whose schema is not entirely known at compile time. For more information
Data Access Programming
Visual C++ provides several ways to work with databases. The preferred way is to use one of the class libraries such as the Active Template Class Library (ATL) or Microsoft Foundation Class (MFC) Library, which simplify working with the database APIs.
The library classes support the following kinds of data access:
ATL provides OLE DB templates and database attributes.
MFC provides Open Database Connectivity (ODBC) and an ODBC driver.
These libraries supply abstractions that simplify working with databases, complete with the speed, power, and flexibility of C++. They integrate your data access work with the library's application framework.
Alternately, you can directly call database API functions from the COM, ODBC, or DAO software development kits (SDKs). For information about programming directly with the COM, DAO, or ODBC API functions, see the COM SDK, DAO SDK, or ODBC SDK.
Use ATL OLE DB if you need to access data, regardless of the form in which it is stored. Use the MFC ODBC classes when you are not using Microsoft Jet (.mdb) databases and want to work with the ODBC API for complete data-source independence. Use the MFC DAO classes when you want to work with Microsoft Jet (.mdb) databases or with external databases such as ODBC data sources.
Installing Database Support Transactions
*** Note ***
Microsoft recommends using OLE DB or ODBC for new projects. DAO should only be used in maintaining existing applications.
OLE DB Programming Overview
What is OLE DB, and what makes it distinct from other database technologies? OLE DB is a high-performance, COM-based database technology produced by Microsoft. What sets OLE DB apart from Microsoft's other database technologies is how it provides Universal Data Access.
Data Access Using ADO.NET in C++
ADO.NET is the .NET Framework API for data access and provides power and ease of use unmatched by previous data access solutions. This section describes some of the issues involving ADO.NET that are unique to C++ users, such as marshaling native types.
ADO.NET runs under the Common Language Runtime (CLR). Therefore, any application that interacts with ADO.NET must also target the CLR. However, that does not mean that native applications cannot use ADO.NET. These examples will demonstrate how to interact with an ADO.NET database from native code.
In This Section
How to: Marshal ANSI Strings for ADO.NET
How to: Marshal BSTR Strings for ADO.NET
How to: Marshal Unicode Strings for ADO.NET
How to: Marshal a VARIANT for ADO.NET
How to: Marshal a SAFEARRAY for ADO.NET
Universal Data Access
Universal Data Access provides a common way to access data regardless of the form in which it is stored. In a typical business situation, a vast amount of information is stored outside of corporate databases. This information is found in file systems (such as FAT or NTFS), indexed-sequential files, personal databases (such as Access), spreadsheets (such as Excel), project planning applications (such as Project), and email (such as Outlook).
Accessing this data using the various associated applications presents a major bottleneck in workflow or at least an annoyance. Most companies find themselves in this situation and deal with the problem by consolidating the information in a database management system (DBMS). However, such a move is expensive, time consuming, and in many cases not practical.
The alternative is to develop a Universal Data Access solution. OLE DB and ADO provide Universal Data Access capability. Of the two, OLE DB is the more performance intensive and is recommended for use with Visual C++ applications.
Universal Data Access implies two capabilities: the first is distributed query or uniform access to multiple (distributed) data sources and the second is the ability to make non-DBMS data sources accessible to database applications.
Distributed query
The ability to access data uniformly on multiple (that is, distributed) data sources. The data sources can be of the same type (such as two separate Access databases) or of different types (such as a SQL Server database and an Access database). Uniformly means that you can meaningfully run the same query on all data sources.
Non-DBMS access
The ability to make non-DBMS data sources accessible to database applications. Examples of DBMS data sources include IMS, DB2, Oracle, SQL Server, Access, and Paradox. Examples of non-DBMS data sources include information in file systems, email, spreadsheets, and project management tools.
Consider a scenario in which a sales department needs to find all email messages received within a one-week period from customers in a certain area. This query might require a search on an email application's mailbox file and a search on an Access table of customers to specify the customers' names. While Access is a DBMS application, Outlook is not.
OLE DB allows you to develop applications that access diverse data sources, whether they are DBMS or not. OLE DB makes universal access possible by using COM interfaces that support the appropriate DBMS functionality for a given data source. COM reduces unnecessary duplication of services and maximized interoperability not only among data sources but also among other applications.
The library classes support the following kinds of data access:
ATL provides OLE DB templates and database attributes.
MFC provides Open Database Connectivity (ODBC) and an ODBC driver.
These libraries supply abstractions that simplify working with databases, complete with the speed, power, and flexibility of C++. They integrate your data access work with the library's application framework.
Alternately, you can directly call database API functions from the COM, ODBC, or DAO software development kits (SDKs). For information about programming directly with the COM, DAO, or ODBC API functions, see the COM SDK, DAO SDK, or ODBC SDK.
Use ATL OLE DB if you need to access data, regardless of the form in which it is stored. Use the MFC ODBC classes when you are not using Microsoft Jet (.mdb) databases and want to work with the ODBC API for complete data-source independence. Use the MFC DAO classes when you want to work with Microsoft Jet (.mdb) databases or with external databases such as ODBC data sources.
Installing Database Support Transactions
*** Note ***
Microsoft recommends using OLE DB or ODBC for new projects. DAO should only be used in maintaining existing applications.
OLE DB Programming Overview
What is OLE DB, and what makes it distinct from other database technologies? OLE DB is a high-performance, COM-based database technology produced by Microsoft. What sets OLE DB apart from Microsoft's other database technologies is how it provides Universal Data Access.
Data Access Using ADO.NET in C++
ADO.NET is the .NET Framework API for data access and provides power and ease of use unmatched by previous data access solutions. This section describes some of the issues involving ADO.NET that are unique to C++ users, such as marshaling native types.
ADO.NET runs under the Common Language Runtime (CLR). Therefore, any application that interacts with ADO.NET must also target the CLR. However, that does not mean that native applications cannot use ADO.NET. These examples will demonstrate how to interact with an ADO.NET database from native code.
In This Section
How to: Marshal ANSI Strings for ADO.NET
How to: Marshal BSTR Strings for ADO.NET
How to: Marshal Unicode Strings for ADO.NET
How to: Marshal a VARIANT for ADO.NET
How to: Marshal a SAFEARRAY for ADO.NET
Universal Data Access
Universal Data Access provides a common way to access data regardless of the form in which it is stored. In a typical business situation, a vast amount of information is stored outside of corporate databases. This information is found in file systems (such as FAT or NTFS), indexed-sequential files, personal databases (such as Access), spreadsheets (such as Excel), project planning applications (such as Project), and email (such as Outlook).
Accessing this data using the various associated applications presents a major bottleneck in workflow or at least an annoyance. Most companies find themselves in this situation and deal with the problem by consolidating the information in a database management system (DBMS). However, such a move is expensive, time consuming, and in many cases not practical.
The alternative is to develop a Universal Data Access solution. OLE DB and ADO provide Universal Data Access capability. Of the two, OLE DB is the more performance intensive and is recommended for use with Visual C++ applications.
Universal Data Access implies two capabilities: the first is distributed query or uniform access to multiple (distributed) data sources and the second is the ability to make non-DBMS data sources accessible to database applications.
Distributed query
The ability to access data uniformly on multiple (that is, distributed) data sources. The data sources can be of the same type (such as two separate Access databases) or of different types (such as a SQL Server database and an Access database). Uniformly means that you can meaningfully run the same query on all data sources.
Non-DBMS access
The ability to make non-DBMS data sources accessible to database applications. Examples of DBMS data sources include IMS, DB2, Oracle, SQL Server, Access, and Paradox. Examples of non-DBMS data sources include information in file systems, email, spreadsheets, and project management tools.
Consider a scenario in which a sales department needs to find all email messages received within a one-week period from customers in a certain area. This query might require a search on an email application's mailbox file and a search on an Access table of customers to specify the customers' names. While Access is a DBMS application, Outlook is not.
OLE DB allows you to develop applications that access diverse data sources, whether they are DBMS or not. OLE DB makes universal access possible by using COM interfaces that support the appropriate DBMS functionality for a given data source. COM reduces unnecessary duplication of services and maximized interoperability not only among data sources but also among other applications.
ClickOnce Deployment for Visual C++ Applications
Visual Studio provides two different technologies for deploying Windows applications: ClickOnce deployment or Windows Installer deployment. For a detailed comparison of ClickOnce and Windows Installer deployment, see Choosing Between ClickOnce and Windows Installer
ClickOnce Deployment in C++The Visual C++ development environment does not directly support deployment of Visual C++ projects with ClickOnce, but tools are available to use it.
Note Visual Studio does support ClickOnce in the Visual C# and Visual Basic development environments. If your Visual C++ project is a dependency of a Visual C# project, you can publish the application (including its dependencies) using ClickOnce deployment from the Visual C# development environment.
To deploy a Visual C++ application using ClickOnce, you first have to build a ClickOnce Application Manifest and a ClickOnce Deployment Manifest using the Manifest Generation and Editing Tool (Mage.exe) or its graphical user interface version (for information, see Manifest Generation and Editing Tool, Graphical Client (MageUI.exe)).
You first use Mage.exe to build the application manifest; the resulting file will have the extension .manifest. You then use Mage.exe to build the deployment manifest; the resulting file will have the extension .application. You then sign the manifests.
The application manifest must specify the target processor (x86, x64, or Itanium). See Deploying 64-bit Applications for information on these options.
Also, the name of the application and deployment manifests must be different from the name of the C++ application. This avoids conflict between the application manifest created by Mage.exe and the external manifest that is part of the C++ application.
Your deployment will need to install any Visual C++ libraries on which your application depends. To determine the dependencies for a particular application, you can use depends.exe or the DUMPBIN utility with the /DEPENDENTS option. For more information on dependencies, see Understanding Dependencies of a Visual C++ Application. You might need to run VCRedist.exe; this utility installs Visual C++ libraries on the target computer.
You may also need to build a bootstrapper (prerequisites installer) for your application to deploy prerequisite components; for information on the bootstrapper, see Adding Custom Prerequisites.
For a more detailed description of the technology, see ClickOnce Deployment. For a detailed example of ClickOnce deployment, see Walkthrough: Deploying a ClickOnce Application Manually.
ReferenceManifest Generation and Editing Tool (Mage.exe)Manifest Generation and Editing Tool, Graphical Client (MageUI.exe)Certificate Creation Tool (Makecert.exe)
ConceptsAdding Custom Prerequisites
Other ResourcesDeployment (C++)Deploying Applications and ComponentsWindows Installer DeploymentClickOnce Deployment.NET Programming in C++Native and .NET Interoperability
ClickOnce Deployment in C++The Visual C++ development environment does not directly support deployment of Visual C++ projects with ClickOnce, but tools are available to use it.
Note Visual Studio does support ClickOnce in the Visual C# and Visual Basic development environments. If your Visual C++ project is a dependency of a Visual C# project, you can publish the application (including its dependencies) using ClickOnce deployment from the Visual C# development environment.
To deploy a Visual C++ application using ClickOnce, you first have to build a ClickOnce Application Manifest and a ClickOnce Deployment Manifest using the Manifest Generation and Editing Tool (Mage.exe) or its graphical user interface version (for information, see Manifest Generation and Editing Tool, Graphical Client (MageUI.exe)).
You first use Mage.exe to build the application manifest; the resulting file will have the extension .manifest. You then use Mage.exe to build the deployment manifest; the resulting file will have the extension .application. You then sign the manifests.
The application manifest must specify the target processor (x86, x64, or Itanium). See Deploying 64-bit Applications for information on these options.
Also, the name of the application and deployment manifests must be different from the name of the C++ application. This avoids conflict between the application manifest created by Mage.exe and the external manifest that is part of the C++ application.
Your deployment will need to install any Visual C++ libraries on which your application depends. To determine the dependencies for a particular application, you can use depends.exe or the DUMPBIN utility with the /DEPENDENTS option. For more information on dependencies, see Understanding Dependencies of a Visual C++ Application. You might need to run VCRedist.exe; this utility installs Visual C++ libraries on the target computer.
You may also need to build a bootstrapper (prerequisites installer) for your application to deploy prerequisite components; for information on the bootstrapper, see Adding Custom Prerequisites.
For a more detailed description of the technology, see ClickOnce Deployment. For a detailed example of ClickOnce deployment, see Walkthrough: Deploying a ClickOnce Application Manually.
ReferenceManifest Generation and Editing Tool (Mage.exe)Manifest Generation and Editing Tool, Graphical Client (MageUI.exe)Certificate Creation Tool (Makecert.exe)
ConceptsAdding Custom Prerequisites
Other ResourcesDeployment (C++)Deploying Applications and ComponentsWindows Installer DeploymentClickOnce Deployment.NET Programming in C++Native and .NET Interoperability
Determining Which DLLs to Redistribute
The first step in determining which files you need to redistribute with your application is to clearly understand the dependencies of this application and collect a list of dependent DLLs by using, for example, Dependency Walker (depends.exe) as described in Understanding Dependencies of a Visual C++ Application.
As you use DUMPBIN or depends.exe to view your dependencies, use the file list in Redist.txt to see which of the DLLs that your application depends on are Microsoft-supplied DLLs that are part of Visual Studio. Redist.txt is located in the Program Files\Microsoft Visual Studio 2005 directory on the second Visual Studio 2005 product CD or on the DVD. Below is a list of Visual C++ files your application might depend on. However, only files specified in Redist.txt may be redistributed with your application. Note that debug versions of an application are not redistributable and that none of the debug versions of the various Visual C++ dynamic-link libraries (DLLs) are redistributable.
Normally, you should not need to redistribute system DLLs (for example, Kernel32.dll, User32.dll, Ole32.dll, or ShDocVW.dll) because these DLLs are part of the operating system and are present on any computer with the same version of the operating system installed. However, there might be exceptions, such as in the case where your application is going to run on several versions of Microsoft operating systems. Be sure to read the corresponding licensing agreements if you encounter such a need. If possible, try to get the system DLLs upgraded either through service packs or by small redistributable packages made available by Microsoft. You can search and identify any such available packages from the Knowledge Base articles in the MSDN Library or at http://support.microsoft.com.
Choosing a Deployment Method
In most cases deployment of Visual C++ applications is done with Windows Installer deployment. For more information on deployment methods supported within Visual Studio and alternatives, see Windows Installer Deployment Overview and Deployment Alternatives. ClickOnce deployment for Visual C++ native applications is not supported in Visual Studio 2005; however, it is possible to deploy Visual C++ applications via ClickOnce on the command line. For more information, see ClickOnce Deployment for Visual C++ Applications.
Visual C++ libraries are side-by-side assembliesVisual Studio 2005 installs Visual C++ libraries as shared side-by-side assemblies. By default, all applications built with Visual Studio 2005 are built as isolated applications with a manifest either embedded as a resource, or accompanying the final binary as an external file. In order to ensure that your Visual C++ application will run on a computer without Visual C++ installed, you may have to redistribute Visual C++ assemblies with your application and ensure they are installed on the target computer.
Redistributing Visual C++ librariesThere are two recommended ways to redistribute Visual C++ DLLs. First, you can use Visual C++ Redistributable Merge Modules to install Visual C++ assemblies as shared side-by-side assemblies. Alternatively, you can install a particular Visual C++ assembly as a private assembly for the application using files provide in the Program Files\Microsoft Visual Studio 8\VC\Redist directory.
Note On Windows Server 2000, Windows 95 and Windows 98, the only recommended and supported way to redistribute Visual C++ libraries is by using Redistributable Merge Modules.
When installing Visual C++ assemblies using redistributable merge modules, the assemblies are deployed as shared side-by-side assemblies into the native assembly cache (WinSxS folder). Access to this folder requires that the installer application be run by a user with administrative rights.
If an installation is run by a user who does not have administrative rights, the installation fails to deploy the Visual C++ assemblies and the application will not run. Also, some products may allow installation on a per-user basis, but merge modules install libraries into shared locations and impact all users of the system. In both these and similar scenarios, the supported technique is to install the required assemblies as private side-by-side assemblies for a particular user's application.
With this technique, it is enough to copy a folder with DLLs and manifests for dependent assemblies to the application's local folder. The operating system's loader, when executing the application, still looks for dependent assemblies in the WinSxS folder first; however when a corresponding assembly cannot be found, the loader loads a private assembly from this sub-directory. More details on this can be found in Redistributing Visual C++ Files.
Manifest requiredIt is not supported to redistribute C/C++ applications that are built without a manifest. Visual C++ libraries cannot be used by C/C++ applications without a manifest binding the application to these library. All C/C++ programs built in Visual C++ 2005 have to include a manifest describing their dependencies on Visual C++ libraries. This is the default setup of projects in Visual Studio and the default behavior of the linker building the final binary from object code.
Applications that expect dependent DLLs to be present in either the application-local folder, or in a folder indicated by an environment variable may also be vulnerable to security-related exploits. It is also more difficult to service such applications after they have been deployed.
Prefer dynamic linking over static linkingIt is not recommended to redistribute C/C++ applications that statically link to Visual C++ libraries. It is often mistakenly assumed that by statically linking your program to Visual C++ libraries it is possible to significantly improve the performance of an application. However the impact on performance of dynamically loading Visual C++ libraries is insignificant in almost all cases. Furthermore, static linking does not allow for servicing the application and its dependent libraries by either the application's author or Microsoft. For example, consider an application that is statically linked to a particular library, running on a client computer with a new version of this library. The application still uses code from the previous version of this library, and does not benefit from library improvements, such as security enhancements. Authors of C/C++ applications are strongly advised to think through the servicing scenario before deciding to statically link to dependent libraries, and use dynamic linking whenever possible.
As you use DUMPBIN or depends.exe to view your dependencies, use the file list in Redist.txt to see which of the DLLs that your application depends on are Microsoft-supplied DLLs that are part of Visual Studio. Redist.txt is located in the Program Files\Microsoft Visual Studio 2005 directory on the second Visual Studio 2005 product CD or on the DVD. Below is a list of Visual C++ files your application might depend on. However, only files specified in Redist.txt may be redistributed with your application. Note that debug versions of an application are not redistributable and that none of the debug versions of the various Visual C++ dynamic-link libraries (DLLs) are redistributable.
Normally, you should not need to redistribute system DLLs (for example, Kernel32.dll, User32.dll, Ole32.dll, or ShDocVW.dll) because these DLLs are part of the operating system and are present on any computer with the same version of the operating system installed. However, there might be exceptions, such as in the case where your application is going to run on several versions of Microsoft operating systems. Be sure to read the corresponding licensing agreements if you encounter such a need. If possible, try to get the system DLLs upgraded either through service packs or by small redistributable packages made available by Microsoft. You can search and identify any such available packages from the Knowledge Base articles in the MSDN Library or at http://support.microsoft.com.
Choosing a Deployment Method
In most cases deployment of Visual C++ applications is done with Windows Installer deployment. For more information on deployment methods supported within Visual Studio and alternatives, see Windows Installer Deployment Overview and Deployment Alternatives. ClickOnce deployment for Visual C++ native applications is not supported in Visual Studio 2005; however, it is possible to deploy Visual C++ applications via ClickOnce on the command line. For more information, see ClickOnce Deployment for Visual C++ Applications.
Visual C++ libraries are side-by-side assembliesVisual Studio 2005 installs Visual C++ libraries as shared side-by-side assemblies. By default, all applications built with Visual Studio 2005 are built as isolated applications with a manifest either embedded as a resource, or accompanying the final binary as an external file. In order to ensure that your Visual C++ application will run on a computer without Visual C++ installed, you may have to redistribute Visual C++ assemblies with your application and ensure they are installed on the target computer.
Redistributing Visual C++ librariesThere are two recommended ways to redistribute Visual C++ DLLs. First, you can use Visual C++ Redistributable Merge Modules to install Visual C++ assemblies as shared side-by-side assemblies. Alternatively, you can install a particular Visual C++ assembly as a private assembly for the application using files provide in the Program Files\Microsoft Visual Studio 8\VC\Redist directory.
Note On Windows Server 2000, Windows 95 and Windows 98, the only recommended and supported way to redistribute Visual C++ libraries is by using Redistributable Merge Modules.
When installing Visual C++ assemblies using redistributable merge modules, the assemblies are deployed as shared side-by-side assemblies into the native assembly cache (WinSxS folder). Access to this folder requires that the installer application be run by a user with administrative rights.
If an installation is run by a user who does not have administrative rights, the installation fails to deploy the Visual C++ assemblies and the application will not run. Also, some products may allow installation on a per-user basis, but merge modules install libraries into shared locations and impact all users of the system. In both these and similar scenarios, the supported technique is to install the required assemblies as private side-by-side assemblies for a particular user's application.
With this technique, it is enough to copy a folder with DLLs and manifests for dependent assemblies to the application's local folder. The operating system's loader, when executing the application, still looks for dependent assemblies in the WinSxS folder first; however when a corresponding assembly cannot be found, the loader loads a private assembly from this sub-directory. More details on this can be found in Redistributing Visual C++ Files.
Manifest requiredIt is not supported to redistribute C/C++ applications that are built without a manifest. Visual C++ libraries cannot be used by C/C++ applications without a manifest binding the application to these library. All C/C++ programs built in Visual C++ 2005 have to include a manifest describing their dependencies on Visual C++ libraries. This is the default setup of projects in Visual Studio and the default behavior of the linker building the final binary from object code.
Applications that expect dependent DLLs to be present in either the application-local folder, or in a folder indicated by an environment variable may also be vulnerable to security-related exploits. It is also more difficult to service such applications after they have been deployed.
Prefer dynamic linking over static linkingIt is not recommended to redistribute C/C++ applications that statically link to Visual C++ libraries. It is often mistakenly assumed that by statically linking your program to Visual C++ libraries it is possible to significantly improve the performance of an application. However the impact on performance of dynamically loading Visual C++ libraries is insignificant in almost all cases. Furthermore, static linking does not allow for servicing the application and its dependent libraries by either the application's author or Microsoft. For example, consider an application that is statically linked to a particular library, running on a client computer with a new version of this library. The application still uses code from the previous version of this library, and does not benefit from library improvements, such as security enhancements. Authors of C/C++ applications are strongly advised to think through the servicing scenario before deciding to statically link to dependent libraries, and use dynamic linking whenever possible.
Deployment Concepts
This section discusses the main considerations for deploying C++ applications.
Windows Installer Deployment in C++Visual C++ projects typically use the traditional Windows Installer setup for deployment. To prepare a Windows Installer deployment, you package your application in a setup.exe file and distribute that file, together with an installer package (.msi). Users then run setup.exe to install your application.
You package your application by adding a Setup project to your solution; when built, it creates the setup and installer package files that you distribute to users. For more information, see Windows Installer Deployment.
Library DependenciesWhen a C/C++ application is built using functionality provided by the Visual C++ libraries, it becomes dependent on the presence of those libraries at runtime. In order for the application to run, it must link, either statically or dynamically, to the necessary Visual C++ libraries. If an application dynamically links to a Visual C++ library, then when it runs that library must be present so it can be loaded. On the other hand, if the application statically links to a Visual C++ library, then it does not need the corresponding DLLs to be present on the user's computer. Static linking, however, has some negative effects, such as the increasing the size of the application files, and making maintenance potentially more difficult. For more information, see Advantages of Using DLLs.
Visual C++ libraries are packaged as DLLs, and all necessary libraries for C/C++ applications are installed by Visual Studio on the developer's computer. However, when deploying your application to your users, it is not feasible in most cases to require them to install Visual Studio in order to run your application. It is important to be able to redistribute just the parts of Visual C++ that are required by your application to run correctly.
This section discusses how to understand what files from Visual C++ you need to redistribute with your applications, what packaging and deployment alternatives are available, and how to resolve some other related issues.Advantages of Using DLLs
Dynamic linking has the following advantages:
Saves memory and reduces swapping. Many processes can use a single DLL simultaneously, sharing a single copy of the DLL in memory. In contrast, Windows must load a copy of the library code into memory for each application that is built with a static link library.
Saves disk space. Many applications can share a single copy of the DLL on disk. In contrast, each application built with a static link library has the library code linked into its executable image as a separate copy.
Upgrades to the DLL are easier. When the functions in a DLL change, the applications that use them do not need to be recompiled or relinked as long as the function arguments and return values do not change. In contrast, statically linked object code requires that the application be relinked when the functions change.
Provides after-market support. For example, a display driver DLL can be modified to support a display that was not available when the application was shipped.
Supports multilanguage programs. Programs written in different programming languages can call the same DLL function as long as the programs follow the function's calling convention. The programs and the DLL function must be compatible in the following ways: the order in which the function expects its arguments to be pushed onto the stack, whether the function or the application is responsible for cleaning up the stack, and whether any arguments are passed in registers.
Provides a mechanism to extend the MFC library classes. You can derive classes from the existing MFC classes and place them in an MFC extension DLL for use by MFC applications.
Eases the creation of international versions. By placing resources in a DLL, it is much easier to create international versions of an application. You can place the strings for each language version of your application in a separate resource DLL and have the different language versions load the appropriate resources.
A potential disadvantage to using DLLs is that the application is not self-contained; it depends on the existence of a separate DLL module.
Windows Installer Deployment in C++Visual C++ projects typically use the traditional Windows Installer setup for deployment. To prepare a Windows Installer deployment, you package your application in a setup.exe file and distribute that file, together with an installer package (.msi). Users then run setup.exe to install your application.
You package your application by adding a Setup project to your solution; when built, it creates the setup and installer package files that you distribute to users. For more information, see Windows Installer Deployment.
Library DependenciesWhen a C/C++ application is built using functionality provided by the Visual C++ libraries, it becomes dependent on the presence of those libraries at runtime. In order for the application to run, it must link, either statically or dynamically, to the necessary Visual C++ libraries. If an application dynamically links to a Visual C++ library, then when it runs that library must be present so it can be loaded. On the other hand, if the application statically links to a Visual C++ library, then it does not need the corresponding DLLs to be present on the user's computer. Static linking, however, has some negative effects, such as the increasing the size of the application files, and making maintenance potentially more difficult. For more information, see Advantages of Using DLLs.
Visual C++ libraries are packaged as DLLs, and all necessary libraries for C/C++ applications are installed by Visual Studio on the developer's computer. However, when deploying your application to your users, it is not feasible in most cases to require them to install Visual Studio in order to run your application. It is important to be able to redistribute just the parts of Visual C++ that are required by your application to run correctly.
This section discusses how to understand what files from Visual C++ you need to redistribute with your applications, what packaging and deployment alternatives are available, and how to resolve some other related issues.Advantages of Using DLLs
Dynamic linking has the following advantages:
Saves memory and reduces swapping. Many processes can use a single DLL simultaneously, sharing a single copy of the DLL in memory. In contrast, Windows must load a copy of the library code into memory for each application that is built with a static link library.
Saves disk space. Many applications can share a single copy of the DLL on disk. In contrast, each application built with a static link library has the library code linked into its executable image as a separate copy.
Upgrades to the DLL are easier. When the functions in a DLL change, the applications that use them do not need to be recompiled or relinked as long as the function arguments and return values do not change. In contrast, statically linked object code requires that the application be relinked when the functions change.
Provides after-market support. For example, a display driver DLL can be modified to support a display that was not available when the application was shipped.
Supports multilanguage programs. Programs written in different programming languages can call the same DLL function as long as the programs follow the function's calling convention. The programs and the DLL function must be compatible in the following ways: the order in which the function expects its arguments to be pushed onto the stack, whether the function or the application is responsible for cleaning up the stack, and whether any arguments are passed in registers.
Provides a mechanism to extend the MFC library classes. You can derive classes from the existing MFC classes and place them in an MFC extension DLL for use by MFC applications.
Eases the creation of international versions. By placing resources in a DLL, it is much easier to create international versions of an application. You can place the strings for each language version of your application in a separate resource DLL and have the different language versions load the appropriate resources.
A potential disadvantage to using DLLs is that the application is not self-contained; it depends on the existence of a separate DLL module.
Deployment (C++)
Deployment is the process by which you distribute a finished application or component to be installed on other computers. Deployment is a multi-stage process that starts when an application is created on a developer's computer and ends when it is installed and ready to run on a user's computer.
Visual Studio provides two different technologies for deploying Windows applications: ClickOnce deployment or Windows Installer deployment.
C++ applications targeting the Common Language Runtime (mixed, pure, and verifiable assemblies) should be deployed using ClickOnce technology. You can use Windows Installer to deploy a managed application, but ClickOnce takes advantage of .NET Framework security features (such as manifest signing) and is therefore recommended. For more information, see ClickOnce Deployment for Visual C++ Applications.
Native C++ applications must be deployed using Windows Installer technology. ClickOnce does not support native C++ applications.
For a detailed comparison of ClickOnce and Windows Installer deployment, see Choosing a Deployment Strategy.
This section discusses how to ensure that a native Visual C++ application runs on any computer that provides a supported target platform, which files you need to include in your installation package, and what are the recommended ways to redistribute the Visual C++ components on which your application depends.
The following topics discuss deployment of Visual C++ applications in more detail.
In This SectionDeployment Concepts
Understanding Dependencies of a Visual C++ Application
Determining Which DLLs to Redistribute
Choosing a Deployment Strategy
Redistributing Visual C++ Files
Deploying Windows-Client Applications
Redistributing Web Applications
Deploying ATL Server Applications
Version Checking of Redistributable Files
ClickOnce Deployment for Visual C++ Applications
Running a C++ /clr Application on a Previous Runtime Version
Visual Studio provides two different technologies for deploying Windows applications: ClickOnce deployment or Windows Installer deployment.
C++ applications targeting the Common Language Runtime (mixed, pure, and verifiable assemblies) should be deployed using ClickOnce technology. You can use Windows Installer to deploy a managed application, but ClickOnce takes advantage of .NET Framework security features (such as manifest signing) and is therefore recommended. For more information, see ClickOnce Deployment for Visual C++ Applications.
Native C++ applications must be deployed using Windows Installer technology. ClickOnce does not support native C++ applications.
For a detailed comparison of ClickOnce and Windows Installer deployment, see Choosing a Deployment Strategy.
This section discusses how to ensure that a native Visual C++ application runs on any computer that provides a supported target platform, which files you need to include in your installation package, and what are the recommended ways to redistribute the Visual C++ components on which your application depends.
The following topics discuss deployment of Visual C++ applications in more detail.
In This SectionDeployment Concepts
Understanding Dependencies of a Visual C++ Application
Determining Which DLLs to Redistribute
Choosing a Deployment Strategy
Redistributing Visual C++ Files
Deploying Windows-Client Applications
Redistributing Web Applications
Deploying ATL Server Applications
Version Checking of Redistributable Files
ClickOnce Deployment for Visual C++ Applications
Running a C++ /clr Application on a Previous Runtime Version
Troubleshooting C/C++ Isolated Applications and Side-by-side Assemblies
Loading a C/C++ application can fail if dependent Visual C++ libraries cannot be found. In this section the most common reasons for a C/C++ application failing to load are described, with proposed steps to resolve the problems.
One of the most common error messages a user will see when dependent Visual C++ DLLs cannot be found is a message box saying “The system cannot execute the specified program”. Below are several things that may help to understand the reason for this error.
1. Follow the steps described in Understanding Dependencies of a Visual C++ Application. The dependency walker can show most dependencies for any particular application or DLL. If you see that some DLLs are missing, install those DLLs on the computer on which you are trying to run your application.
2. A manifest is used by the operating system loader to load assemblies that your application depends on. It can either be embedded inside the binary as a resource, or saved as an external file in the application's local folder. To check whether the manifest is embedded inside the binary, open your binary in Visual Studio and browse through the resources of this binary. You should be able to find a resource named RT_MANIFEST. If you cannot find a manifest embedded inside the binary, check for an external file named something like..manifest.
3. If a manifest is not present, you need to ensure that the linker generates a manifest for your project. You need to check the linker option Generate manifest in the Project Properties dialog for this project.
Note Building Visual C++ projects without manifest generation is not supported. Any C/C++ program built in Visual C++ 2005 has to include a manifest describing its dependencies on Visual C++ libraries.
4. If the manifest is embedded inside the binary, ensure that the ID of RT_MANIFEST is correct for this type of the binary. For applications, ID should be equal to 1, for most DLLs ID should be equal to 2. If the manifest is in an external file, open it in an XML editor or text editor. For more information on manifests and rules for deployment, see Manifests.
Note On Windows XP, if an external manifest is present in the application's local folder, the operating system loader uses this manifest instead of a manifest embedded inside the binary. On Windows Server 2003 and later versions of Windows, the opposite is true—the external manifest is ignored and the embedded manifest is used when present.
5. It is recommended that all DLLs have a manifest embedded inside the binary. External manifests are ignored when a DLL is loaded though a LoadLibrary call. For more information, see Assembly manifests.
6. Check that all assemblies enumerated in the manifest are correctly installed on the computer. Each assembly is specified in the manifest by its name, version number and processor architecture. If your application depends on side-by-side assemblies, check that these assemblies are installed on the computer properly, so they can be found by the operating system loader using the steps specified in Assembly Searching Sequence. Remember that 64-bit assemblies cannot be loaded in 32-bit processes and cannot be executed on 32-bit operating systems.
One of the most common error messages a user will see when dependent Visual C++ DLLs cannot be found is a message box saying “The system cannot execute the specified program”. Below are several things that may help to understand the reason for this error.
1. Follow the steps described in Understanding Dependencies of a Visual C++ Application. The dependency walker can show most dependencies for any particular application or DLL. If you see that some DLLs are missing, install those DLLs on the computer on which you are trying to run your application.
2. A manifest is used by the operating system loader to load assemblies that your application depends on. It can either be embedded inside the binary as a resource, or saved as an external file in the application's local folder. To check whether the manifest is embedded inside the binary, open your binary in Visual Studio and browse through the resources of this binary. You should be able to find a resource named RT_MANIFEST. If you cannot find a manifest embedded inside the binary, check for an external file named something like
3. If a manifest is not present, you need to ensure that the linker generates a manifest for your project. You need to check the linker option Generate manifest in the Project Properties dialog for this project.
Note Building Visual C++ projects without manifest generation is not supported. Any C/C++ program built in Visual C++ 2005 has to include a manifest describing its dependencies on Visual C++ libraries.
4. If the manifest is embedded inside the binary, ensure that the ID of RT_MANIFEST is correct for this type of the binary. For applications, ID should be equal to 1, for most DLLs ID should be equal to 2. If the manifest is in an external file, open it in an XML editor or text editor. For more information on manifests and rules for deployment, see Manifests.
Note On Windows XP, if an external manifest is present in the application's local folder, the operating system loader uses this manifest instead of a manifest embedded inside the binary. On Windows Server 2003 and later versions of Windows, the opposite is true—the external manifest is ignored and the embedded manifest is used when present.
5. It is recommended that all DLLs have a manifest embedded inside the binary. External manifests are ignored when a DLL is loaded though a LoadLibrary call. For more information, see Assembly manifests.
6. Check that all assemblies enumerated in the manifest are correctly installed on the computer. Each assembly is specified in the manifest by its name, version number and processor architecture. If your application depends on side-by-side assemblies, check that these assemblies are installed on the computer properly, so they can be found by the operating system loader using the steps specified in Assembly Searching Sequence. Remember that 64-bit assemblies cannot be loaded in 32-bit processes and cannot be executed on 32-bit operating systems.
Understanding Manifest Generation for C/C++ Programs
A manifest is an XML document that can be an external XML file or a resource embedded inside an application or an assembly. The manifest of an isolated application is used to manage the names and versions of shared side-by-side assemblies to which the application should bind at run time. The manifest of a side-by-side assembly specifies its dependencies on names, versions, resources, and other assemblies.
There are two ways to create a manifest for an isolated application or a side-by-side assembly. First, the author of the assembly can manually create a manifest file following rules and naming requirements. Alternatively, if a program only depends on Visual C++ assemblies such as CRT, MFC, ATL or others, then a manifest can be generated automatically by the linker.
The headers of Visual C++ libraries contain assembly information, and when the libraries are included in application code, this assembly information is used by the linker to form a manifest for the final binary. The linker does not embed the manifest file inside the binary, and can only generate the manifest as an external file. Having a manifest as an external file may not work for all scenarios. For example, it is recommended that private assemblies have embedded manifests. In command line builds such as those that use nmake to build code, a manifest can be embedded using the manifest tool; for more information see Manifest Generation at the Command Line. When building in Visual Studio, a manifest can be embedded by setting a property for the manifest tool in the Project Properties dialog; see Manifest Generation in Visual Studio.
Manifest Generation in Visual Studio
Generation of a manifest file for a particular project can be controlled in the project Property Pages dialog. On the Configuration Properties tab, click Linker, then Manifest File, then Generate Manifest. By default the project properties of new projects are set to generate a manifest file. However it is possible to disable generation of the manifest for a project using the Generate Manifest property of the project. When this property is set to Yes, the manifest for this project is generated. Otherwise the linker ignores assembly information when resolving dependencies of the application code, and does not generate the manifest.
The build system in Visual Studio allows the manifest to be embedded in the final binary application file, or generated as an external file. This behavior is controlled by the Embed Manifest option in the Project Properties dialog. To set this property, open the Manifest Tool node, then select Input and Output. If the manifest is not embedded, it is generated as an external file and saved in the same directory as the final binary. If the manifest is embedded, Visual Studio embeds the final manifests using the following process:
1. After the source code is compiled to object files, the linker collects dependent assembly information. While linking the final binary, the linker generates an intermediate manifest that is used later to generate the final manifest.
2. After the intermediate manifest and linking are finished, the manifest tool will be executed to merge a final manifest and save it as an external file.
3. The project build system then detects whether the manifest generated by the manifest tool contains different information than the manifest already embedded in the binary.
4. If the manifest embedded in the binary is different from the manifest generated by the manifest tool, or the binary does not contain an embedded manifest, Visual Studio will invoke the linker one more time to embed the external manifest file inside the binary as a resource.
5. If the manifest embedded in the binary is the same as the manifest generated by the manifest tool, the build will continue to the next build steps.
The manifest is embedded inside the final binary as a text resource and it can be viewed by opening the final binary as a file in Visual Studio. To ensure that the manifest points to the correct libraries, follow the steps described in Understanding Dependencies of a Visual C++ Application or follow the suggestions described in the Troubleshooting section.
There are two ways to create a manifest for an isolated application or a side-by-side assembly. First, the author of the assembly can manually create a manifest file following rules and naming requirements. Alternatively, if a program only depends on Visual C++ assemblies such as CRT, MFC, ATL or others, then a manifest can be generated automatically by the linker.
The headers of Visual C++ libraries contain assembly information, and when the libraries are included in application code, this assembly information is used by the linker to form a manifest for the final binary. The linker does not embed the manifest file inside the binary, and can only generate the manifest as an external file. Having a manifest as an external file may not work for all scenarios. For example, it is recommended that private assemblies have embedded manifests. In command line builds such as those that use nmake to build code, a manifest can be embedded using the manifest tool; for more information see Manifest Generation at the Command Line. When building in Visual Studio, a manifest can be embedded by setting a property for the manifest tool in the Project Properties dialog; see Manifest Generation in Visual Studio.
Manifest Generation in Visual Studio
Generation of a manifest file for a particular project can be controlled in the project Property Pages dialog. On the Configuration Properties tab, click Linker, then Manifest File, then Generate Manifest. By default the project properties of new projects are set to generate a manifest file. However it is possible to disable generation of the manifest for a project using the Generate Manifest property of the project. When this property is set to Yes, the manifest for this project is generated. Otherwise the linker ignores assembly information when resolving dependencies of the application code, and does not generate the manifest.
The build system in Visual Studio allows the manifest to be embedded in the final binary application file, or generated as an external file. This behavior is controlled by the Embed Manifest option in the Project Properties dialog. To set this property, open the Manifest Tool node, then select Input and Output. If the manifest is not embedded, it is generated as an external file and saved in the same directory as the final binary. If the manifest is embedded, Visual Studio embeds the final manifests using the following process:
1. After the source code is compiled to object files, the linker collects dependent assembly information. While linking the final binary, the linker generates an intermediate manifest that is used later to generate the final manifest.
2. After the intermediate manifest and linking are finished, the manifest tool will be executed to merge a final manifest and save it as an external file.
3. The project build system then detects whether the manifest generated by the manifest tool contains different information than the manifest already embedded in the binary.
4. If the manifest embedded in the binary is different from the manifest generated by the manifest tool, or the binary does not contain an embedded manifest, Visual Studio will invoke the linker one more time to embed the external manifest file inside the binary as a resource.
5. If the manifest embedded in the binary is the same as the manifest generated by the manifest tool, the build will continue to the next build steps.
The manifest is embedded inside the final binary as a text resource and it can be viewed by opening the final binary as a file in Visual Studio. To ensure that the manifest points to the correct libraries, follow the steps described in Understanding Dependencies of a Visual C++ Application or follow the suggestions described in the Troubleshooting section.
Concepts of Isolated Applications and Side-by-side Assemblies
An application is considered an isolated application if all of its components are side-by-side assemblies. A side-by-side assembly is a collection of resources—a group of DLLs, windows classes, COM servers, type libraries, or interfaces—available for an application to use at runtime. Typically, a side-by-side assembly is one to several DLLs. For example, the C Runtime Library assembly contains three DLLs—msvcr80.dll, msvcm80.dll and msvcp80.dll—and is used by applications when they are built using functions from the CRT library.
Shared or privateA side-by-side assembly can be either shared or private. Shared side-by-side assemblies may be used by multiple applications that specify, in their manifests, a dependence on the assembly. Multiple versions of side-by-side assemblies can be shared by different applications running at the same time. A private assembly is an assembly that is deployed with an application and is available for the exclusive use of that application. Private assemblies are installed in the folder containing the application's executable file or one of its subfolders.
Manifests and search orderBoth isolated applications and side-by-side assemblies are described by manifests. A manifest is an XML document that can be an external XML file or embedded inside an application or an assembly as a resource. The manifest file of an isolated application is used to manage the names and versions of shared side-by-side assemblies to which the application should bind at run time. The manifest of a side-by-side assembly specifies names, versions, resources, and dependent assemblies of side-by-side assemblies. For a shared side-by-side assembly, its manifest is installed in the WinSxS\Manifests folder. In the case of a private assembly, it is recommended to include its manifest in the DLL as a resource with ID equal to 1, and the name of the private assembly may be the same as the name of the DLL. For more information, see Private Assemblies.
At execution time, Windows uses assembly information from the application's manifest to search and load the corresponding side-by-side assembly. If an isolated application specifies an assembly dependency, the operating system first searches for the assembly among the shared assemblies in the WinSxS folder. If the required assembly is not found, the operating system then searches for a private assembly installed in a folder of the application's directory structure. For more information, see Assembly Searching Sequence.
Changing dependenciesIt is possible to change side-by-side assembly dependencies after an application has been deployed by modifying the Publisher Configuration Files and Application Configuration Files. A publisher configuration file, also called a publisher policy file, is an XML file that globally redirects applications and assemblies from using one version of a side-by-side assembly to another version of the same assembly. A good example when changing dependency may be used is when a bug fix or security fix is deployed for a particular side-by-side assembly and a publisher of this assembly would like to redirect all applications to use the new version of the assembly. An application configuration file is an XML file that redirects a specific application from using one version of a side-by-side assembly to another version of the same assembly. It may be used to redirect a particular application to use a version of a side-by-side assembly different than the one defined in the global publisher configuration file. For more information, see Configuration.
Visual C++ librariesIn Visual C++ 2005, libraries such as ATL, MFC, CRT, Standard C++, OpenMP, and MSDIA are deployed as shared side-by-side assemblies to the native assembly cache. By default, all applications built with Visual C++ 2005 are built with the manifest embedded inside the final binary, which describes the dependencies of this binary on the Visual C++ libraries. To understand manifest generation for Visual C++ applications, see Understanding Manifest Generation for C/C++ Programs
Shared or privateA side-by-side assembly can be either shared or private. Shared side-by-side assemblies may be used by multiple applications that specify, in their manifests, a dependence on the assembly. Multiple versions of side-by-side assemblies can be shared by different applications running at the same time. A private assembly is an assembly that is deployed with an application and is available for the exclusive use of that application. Private assemblies are installed in the folder containing the application's executable file or one of its subfolders.
Manifests and search orderBoth isolated applications and side-by-side assemblies are described by manifests. A manifest is an XML document that can be an external XML file or embedded inside an application or an assembly as a resource. The manifest file of an isolated application is used to manage the names and versions of shared side-by-side assemblies to which the application should bind at run time. The manifest of a side-by-side assembly specifies names, versions, resources, and dependent assemblies of side-by-side assemblies. For a shared side-by-side assembly, its manifest is installed in the WinSxS\Manifests folder. In the case of a private assembly, it is recommended to include its manifest in the DLL as a resource with ID equal to 1, and the name of the private assembly may be the same as the name of the DLL. For more information, see Private Assemblies.
At execution time, Windows uses assembly information from the application's manifest to search and load the corresponding side-by-side assembly. If an isolated application specifies an assembly dependency, the operating system first searches for the assembly among the shared assemblies in the WinSxS folder. If the required assembly is not found, the operating system then searches for a private assembly installed in a folder of the application's directory structure. For more information, see Assembly Searching Sequence.
Changing dependenciesIt is possible to change side-by-side assembly dependencies after an application has been deployed by modifying the Publisher Configuration Files and Application Configuration Files. A publisher configuration file, also called a publisher policy file, is an XML file that globally redirects applications and assemblies from using one version of a side-by-side assembly to another version of the same assembly. A good example when changing dependency may be used is when a bug fix or security fix is deployed for a particular side-by-side assembly and a publisher of this assembly would like to redirect all applications to use the new version of the assembly. An application configuration file is an XML file that redirects a specific application from using one version of a side-by-side assembly to another version of the same assembly. It may be used to redirect a particular application to use a version of a side-by-side assembly different than the one defined in the global publisher configuration file. For more information, see Configuration.
Visual C++ librariesIn Visual C++ 2005, libraries such as ATL, MFC, CRT, Standard C++, OpenMP, and MSDIA are deployed as shared side-by-side assemblies to the native assembly cache. By default, all applications built with Visual C++ 2005 are built with the manifest embedded inside the final binary, which describes the dependencies of this binary on the Visual C++ libraries. To understand manifest generation for Visual C++ applications, see Understanding Manifest Generation for C/C++ Programs
Redistributing Visual C++ Files
not only a good development environment, but is also a convenient environment on which to run and test applications. However, when you want to deploy your application to other computers, you need to redistribute all the files needed to support the application on the target system. For more information on which files you may need to redistribute with your application, see Determining Which DLLs to Redistribute.
Only some Visual C++ files are allowed to be redistributed with your application. Please consult the EULA for Visual Studio 2005 and the Redist.txt file to see which files may be redistributed with your application. EULA.txt can be found in the \Setup directory on the first Visual Studio 2005 product CD or on the DVD, and Redist.txt is located in the Program Files\Microsoft Visual Studio 2005 directory on the second CD or on the DVD.
Visual C++ files can be redistributed using either the provided Redistributable Merge Modules, or by deploying specific Visual C++ assemblies as private side-by-side assemblies in the application local folder.
In the first case, a merge module with a specific Visual C++ assembly has to be included in a Windows Installer package or similar installation package used to deploy this application to another computer. For more information, see Redistributing Using Merge Modules.
When deploying a Visual C++ assembly as a private side-by-side assembly, all DLLs and the manifest file that form this assembly have to be added to the Windows Installer or similar installation package and deployed to the target computer in a subdirectory in the application local folder, following the rules for deploying private assemblies. Information on which Visual C++ DLLs and manifest files are part of which Visual C++ assemblies can be found in Visual C++ Libraries as Side-by-Side Shared Assemblies. A description of the rules that must be followed when deploying private assemblies for loading at runtime can be found in Assembly Searching Sequence.
Redistributing Using Merge Modules
Visual Studio installs several merge modules for each Visual C++ component that may be redistributed with your application. They may be found in the Program Files\Common Files\Merge Modules folder. Each of these merge modules may be used to deploy Visual C++ DLLs to the target system. However only non-debug versions of Visual C++ DLLs are allowed to be redistributed. For a complete list of merge modules that are allowed to be used redistributed, please see Redist.txt.
Using Visual C++ redistributable merge modules, you can install Visual C++ assemblies as shared side-by-side assemblies into the native assembly cache (WinSxS folder). Visual Studio itself uses this technique to install these DLLs. Installation of the WinSxS folder requires administrative user rights. If an installation is run by a user who does not have administrative rights, the Visual C++ assemblies cannot be installed, and applications that depend on those DLLs cannot run.
The alternative redistribution approach is to install private side-by-side assemblies of a particular user application. For more information on deploying Visual C++ files as private assemblies see Redistributing Visual C++ Files.
Only some Visual C++ files are allowed to be redistributed with your application. Please consult the EULA for Visual Studio 2005 and the Redist.txt file to see which files may be redistributed with your application. EULA.txt can be found in the \Setup directory on the first Visual Studio 2005 product CD or on the DVD, and Redist.txt is located in the Program Files\Microsoft Visual Studio 2005 directory on the second CD or on the DVD.
Visual C++ files can be redistributed using either the provided Redistributable Merge Modules, or by deploying specific Visual C++ assemblies as private side-by-side assemblies in the application local folder.
In the first case, a merge module with a specific Visual C++ assembly has to be included in a Windows Installer package or similar installation package used to deploy this application to another computer. For more information, see Redistributing Using Merge Modules.
When deploying a Visual C++ assembly as a private side-by-side assembly, all DLLs and the manifest file that form this assembly have to be added to the Windows Installer or similar installation package and deployed to the target computer in a subdirectory in the application local folder, following the rules for deploying private assemblies. Information on which Visual C++ DLLs and manifest files are part of which Visual C++ assemblies can be found in Visual C++ Libraries as Side-by-Side Shared Assemblies. A description of the rules that must be followed when deploying private assemblies for loading at runtime can be found in Assembly Searching Sequence.
Redistributing Using Merge Modules
Visual Studio installs several merge modules for each Visual C++ component that may be redistributed with your application. They may be found in the Program Files\Common Files\Merge Modules folder. Each of these merge modules may be used to deploy Visual C++ DLLs to the target system. However only non-debug versions of Visual C++ DLLs are allowed to be redistributed. For a complete list of merge modules that are allowed to be used redistributed, please see Redist.txt.
Using Visual C++ redistributable merge modules, you can install Visual C++ assemblies as shared side-by-side assemblies into the native assembly cache (WinSxS folder). Visual Studio itself uses this technique to install these DLLs. Installation of the WinSxS folder requires administrative user rights. If an installation is run by a user who does not have administrative rights, the Visual C++ assemblies cannot be installed, and applications that depend on those DLLs cannot run.
The alternative redistribution approach is to install private side-by-side assemblies of a particular user application. For more information on deploying Visual C++ files as private assemblies see Redistributing Visual C++ Files.
Building C/C++ Isolated Applications and Side-by-side Assemblies
Visual C++ 2005 supports a new deployment model for Windows client applications based on the idea of isolated applications and side-by-side assemblies. In Visual C++ 2005, the ATL, MFC, Standard C++, and CRT libraries have been rebuilt as shared side-by-side assemblies that are installed into the native assembly cache (WinSxS folder). By default, Visual C++ 2005 builds all native C/C++ applications as isolated applications that use manifests to describe their dependencies on Visual C++ libraries.
Building C/C++ programs as isolated applications presents a range of advantages. For example, an isolated application is unaffected when other C/C++ applications install or uninstall Visual C++ libraries. Visual C++ libraries used by isolated applications may still be redistributed in either the application's local folder, or by installation to the native assembly cache (WinSxS); however, servicing of Visual C++ libraries for already deployed applications can be simplified by using a publisher configuration file. The isolated application deployment model makes it easier to ensure that C/C++ applications that are running on a specific computer use the most recent version of Visual C++ libraries, while still leaving open the possibility for system administrators and application authors to control explicit version binding of applications to their dependent DLLs.
This section discusses how you can build your C/C++ application as an isolated application and ensure that it binds to Visual C++ libraries using a manifest. The information in this section primarily applies to native, or unmanaged, Visual C++ applications. For information about deploying native applications built with Visual C++ 2005, see Redistributing Visual C++ Files.
In This Section
Concepts of Isolated Applications and Side-by-side Assemblies
Understanding Manifest Generation for C/C++ Programs
Troubleshooting C/C++ Isolated Applications and Side-by-side Assemblies
Related SectionsIsolated Applications and Side-by-side Assemblies
Deployment (C++)
Building C/C++ programs as isolated applications presents a range of advantages. For example, an isolated application is unaffected when other C/C++ applications install or uninstall Visual C++ libraries. Visual C++ libraries used by isolated applications may still be redistributed in either the application's local folder, or by installation to the native assembly cache (WinSxS); however, servicing of Visual C++ libraries for already deployed applications can be simplified by using a publisher configuration file. The isolated application deployment model makes it easier to ensure that C/C++ applications that are running on a specific computer use the most recent version of Visual C++ libraries, while still leaving open the possibility for system administrators and application authors to control explicit version binding of applications to their dependent DLLs.
This section discusses how you can build your C/C++ application as an isolated application and ensure that it binds to Visual C++ libraries using a manifest. The information in this section primarily applies to native, or unmanaged, Visual C++ applications. For information about deploying native applications built with Visual C++ 2005, see Redistributing Visual C++ Files.
In This Section
Concepts of Isolated Applications and Side-by-side Assemblies
Understanding Manifest Generation for C/C++ Programs
Troubleshooting C/C++ Isolated Applications and Side-by-side Assemblies
Related SectionsIsolated Applications and Side-by-side Assemblies
Deployment (C++)
The Debug Class in Visual C++
When using Debug in a Visual C++ application, the behavior does not change between a debug and a release build.
RemarksThe behavior for Trace is identical to the behavior for the Debug class, but is dependent on the symbol TRACE being defined. This means that you must #ifdef any Trace-related code to prevent debug behavior in a release build.
ExampleThe following sample always executes the output statements, regardless of whether you compile with /DDEBUG or /DTRACE.
// mcpp_debug_class.cpp// compile with: /clr#usingusing namespace System::Diagnostics;using namespace System;
int main() {Trace::Listeners->Add( gcnew TextWriterTraceListener( Console::Out ) );Trace::AutoFlush = true;Trace::Indent();Trace::WriteLine( "Entering Main" );Console::WriteLine( "Hello World." );Trace::WriteLine( "Exiting Main" );Trace::Unindent();
Debug::WriteLine("test");}
OutputEntering MainHello World.Exiting Maintest
ExampleTo get the expected behavior (that is, no "test" output printed for a release build), you must use the #ifdef and #endif directives. The previous code sample is modified below to demonstrate this fix:
// mcpp_debug_class2.cpp// compile with: /clr#usingusing namespace System::Diagnostics;using namespace System;
int main() {Trace::Listeners->Add( gcnew TextWriterTraceListener( Console::Out ) );Trace::AutoFlush = true;Trace::Indent();
#ifdef TRACE // checks for a debug buildTrace::WriteLine( "Entering Main" );Console::WriteLine( "Hello World." );Trace::WriteLine( "Exiting Main" );#endifTrace::Unindent();
#ifdef DEBUG // checks for a debug buildDebug::WriteLine("test");#endif //ends the conditional block}
RemarksThe behavior for Trace is identical to the behavior for the Debug class, but is dependent on the symbol TRACE being defined. This means that you must #ifdef any Trace-related code to prevent debug behavior in a release build.
ExampleThe following sample always executes the output statements, regardless of whether you compile with /DDEBUG or /DTRACE.
// mcpp_debug_class.cpp// compile with: /clr#using
int main() {Trace::Listeners->Add( gcnew TextWriterTraceListener( Console::Out ) );Trace::AutoFlush = true;Trace::Indent();Trace::WriteLine( "Entering Main" );Console::WriteLine( "Hello World." );Trace::WriteLine( "Exiting Main" );Trace::Unindent();
Debug::WriteLine("test");}
OutputEntering MainHello World.Exiting Maintest
ExampleTo get the expected behavior (that is, no "test" output printed for a release build), you must use the #ifdef and #endif directives. The previous code sample is modified below to demonstrate this fix:
// mcpp_debug_class2.cpp// compile with: /clr#using
int main() {Trace::Listeners->Add( gcnew TextWriterTraceListener( Console::Out ) );Trace::AutoFlush = true;Trace::Indent();
#ifdef TRACE // checks for a debug buildTrace::WriteLine( "Entering Main" );Console::WriteLine( "Hello World." );Trace::WriteLine( "Exiting Main" );#endifTrace::Unindent();
#ifdef DEBUG // checks for a debug buildDebug::WriteLine("test");#endif //ends the conditional block}
Class-Member Declaration Syntax
Class data members and function members are generally declared following the rules for declarations. They consist of, in this order:
Declaration specifiers. In classes, the storage class specifiers static and mutable are allowed for data members. The cv-qualifiers const and volatile are allowed for data and function members. The declaration specifiers friend, static, virtual and inline are allowed for functions, although friend indicates a non-member function.
Declarators without initializers. In the case of virtual functions, the pure specifier of the form = 0 is used after the function declarator to specify a pure virtual function (a virtual function without an implementation in that class).
Optionally, bit fields. See Bit Fields.
OR
Function definitions. The definition of a function can be included in the class. If a member function is so defined, it is automatically considered inline.
OR
Member templates (see the comments on C++ member templates in Members of Class Templates).
Member data cannot be declared as auto, extern, or register storage class. They can, however, be declared as having static storage class.
When you declare a friend class in a member list, you can omit the member declarator list. For more information on friends, see friend Specifier and Friends. Even if a class name has not been introduced, it can be used in a friend declaration. This friend declaration introduces the name. However, in member declarations for such classes, the elaborated type specifier syntax must be used, as shown in the following example:
// class_member_declaration_syntax.cpp
// compile with: /c
struct HasFriends {
friend class NotDeclaredYet;
};
In the preceding example, there is no member declarator list after the class declaration. Because the declaration for NotDeclaredYet has not yet been processed, the elaborated type specifier form is used: class NotDeclaredYet. A type that has been declared can be specified in a friend member declaration using a normal type specifier:
// class_member_declaration_syntax2.cpp
// compile with: /c
struct AlreadyDeclared {};
struct HasFriends {
friend AlreadyDeclared;
};
The pure specifier (shown in the following example) indicates that no implementation is supplied for the virtual function being declared. Therefore, the pure specifier can be specified only on virtual functions. Consider this example:
// class_member_declaration_syntax3.cpp
// compile with: /c
class StrBase { // Base class for strings.
public:
virtual int IsLessThan( StrBase& ) = 0;
virtual int IsEqualTo( StrBase& ) = 0;
virtual StrBase& CopyOf( StrBase& ) = 0;
};
The preceding code declares an abstract base class — that is, a class designed to be used only as the base class for more specific classes. Such base classes can enforce a particular protocol, or set of functionality, by declaring one or more virtual functions as "pure" virtual functions, using the pure specifier.
Classes that inherit from the StrBase class must provide implementations for the pure virtual functions; otherwise, they, too, are considered abstract base classes.
Abstract base classes cannot be used to declare objects. For example, before an object of a type inherited from StrBase can be declared, the functions IsLessThan, IsEqualTo, and CopyOf must be implemented. (For more information about abstract base classes, see Abstract Classes.)
Declaration specifiers. In classes, the storage class specifiers static and mutable are allowed for data members. The cv-qualifiers const and volatile are allowed for data and function members. The declaration specifiers friend, static, virtual and inline are allowed for functions, although friend indicates a non-member function.
Declarators without initializers. In the case of virtual functions, the pure specifier of the form = 0 is used after the function declarator to specify a pure virtual function (a virtual function without an implementation in that class).
Optionally, bit fields. See Bit Fields.
OR
Function definitions. The definition of a function can be included in the class. If a member function is so defined, it is automatically considered inline.
OR
Member templates (see the comments on C++ member templates in Members of Class Templates).
Member data cannot be declared as auto, extern, or register storage class. They can, however, be declared as having static storage class.
When you declare a friend class in a member list, you can omit the member declarator list. For more information on friends, see friend Specifier and Friends. Even if a class name has not been introduced, it can be used in a friend declaration. This friend declaration introduces the name. However, in member declarations for such classes, the elaborated type specifier syntax must be used, as shown in the following example:
// class_member_declaration_syntax.cpp
// compile with: /c
struct HasFriends {
friend class NotDeclaredYet;
};
In the preceding example, there is no member declarator list after the class declaration. Because the declaration for NotDeclaredYet has not yet been processed, the elaborated type specifier form is used: class NotDeclaredYet. A type that has been declared can be specified in a friend member declaration using a normal type specifier:
// class_member_declaration_syntax2.cpp
// compile with: /c
struct AlreadyDeclared {};
struct HasFriends {
friend AlreadyDeclared;
};
The pure specifier (shown in the following example) indicates that no implementation is supplied for the virtual function being declared. Therefore, the pure specifier can be specified only on virtual functions. Consider this example:
// class_member_declaration_syntax3.cpp
// compile with: /c
class StrBase { // Base class for strings.
public:
virtual int IsLessThan( StrBase& ) = 0;
virtual int IsEqualTo( StrBase& ) = 0;
virtual StrBase& CopyOf( StrBase& ) = 0;
};
The preceding code declares an abstract base class — that is, a class designed to be used only as the base class for more specific classes. Such base classes can enforce a particular protocol, or set of functionality, by declaring one or more virtual functions as "pure" virtual functions, using the pure specifier.
Classes that inherit from the StrBase class must provide implementations for the pure virtual functions; otherwise, they, too, are considered abstract base classes.
Abstract base classes cannot be used to declare objects. For example, before an object of a type inherited from StrBase can be declared, the functions IsLessThan, IsEqualTo, and CopyOf must be implemented. (For more information about abstract base classes, see Abstract Classes.)
Compile a C++ Program that Targets the CLR in Visual Studio
You can create C++ programs that use .NET classes and compile them using the Visual Studio Development Environment.
For this procedure you can type in your own C++ program or use one of the sample programs. The sample program referred to in this procedure creates a text file named textfile.txt and saves it to the project directory.
To create a new project in Visual Studio and add a new source file
1. Create a new project. On the File menu, point to New, then click Project….
2. From the Visual C++ project types, click CLR, then click CLR Empty Project.
3. Enter a project name.
By default, the solution that contains the project has the same name as the new project, though you can enter a different name. You can enter a different location for the project if you wish.
Click OK to create the new project.
4. If Solution Explorer is not visible, click Solution Explorer on the View menu.
5. Add a new source file to the project:
Right-click on the Source Files folder in Solution Explorer and point to Add and click New Item….
Click C++ File (.cpp) and enter a file name then click Add.
The .cpp file appears in the Source Files folder in Solution Explorer and a tabbed window appears where you type the code you want in that file.
6. Click in the newly created tab in Visual Studio and type in a valid C++ program or copy and paste one of the sample programs.
7. On the Build menu, click Build Solution.
The Output window displays information about the compilation progress, such as the location of the build log and a message indicating that the build succeeded.
If you make changes and run the program without doing a build, a dialog may appear indicating the project is out of date. Select the checkbox on this dialog before you click OK if you want Visual Studio to always use the current versions of files when building without prompting you.
8. On the Debug menu, click Start without Debugging.
9. If you used the sample program, a command window is displayed that indicates the text file has been created. Press any key to close the command window.
The textfile.txt text file that was created is located in your project directory. You can open this file with Notepad.
For this procedure you can type in your own C++ program or use one of the sample programs. The sample program referred to in this procedure creates a text file named textfile.txt and saves it to the project directory.
To create a new project in Visual Studio and add a new source file
1. Create a new project. On the File menu, point to New, then click Project….
2. From the Visual C++ project types, click CLR, then click CLR Empty Project.
3. Enter a project name.
By default, the solution that contains the project has the same name as the new project, though you can enter a different name. You can enter a different location for the project if you wish.
Click OK to create the new project.
4. If Solution Explorer is not visible, click Solution Explorer on the View menu.
5. Add a new source file to the project:
Right-click on the Source Files folder in Solution Explorer and point to Add and click New Item….
Click C++ File (.cpp) and enter a file name then click Add.
The .cpp file appears in the Source Files folder in Solution Explorer and a tabbed window appears where you type the code you want in that file.
6. Click in the newly created tab in Visual Studio and type in a valid C++ program or copy and paste one of the sample programs.
7. On the Build menu, click Build Solution.
The Output window displays information about the compilation progress, such as the location of the build log and a message indicating that the build succeeded.
If you make changes and run the program without doing a build, a dialog may appear indicating the project is out of date. Select the checkbox on this dialog before you click OK if you want Visual Studio to always use the current versions of files when building without prompting you.
8. On the Debug menu, click Start without Debugging.
9. If you used the sample program, a command window is displayed that indicates the text file has been created. Press any key to close the command window.
The textfile.txt text file that was created is located in your project directory. You can open this file with Notepad.
Visual C++ 2005 Workshop
With Visual C++ Express Edition, you can create Visual C++ .NET projects, including Windows Forms applications. You can also create C and C++ programs that conform to ANSI and ISO standards.
The Visual C++ Express Edition provides a subset of the functionality available in other Visual C++ editions. As such, some components, libraries, or features available in these editions are not available in this version of the product. For these features, you would need to upgrade to another version of Visual C++. For more information on these editions
The Visual C++ Express Edition provides a subset of the functionality available in other Visual C++ editions. As such, some components, libraries, or features available in these editions are not available in this version of the product. For these features, you would need to upgrade to another version of Visual C++. For more information on these editions
สมัครสมาชิก:
บทความ (Atom)