C cli windows forms

Программирование .NET с использованием C++/CLI .NET programming with C++/CLI

По умолчанию проекты CLR, созданные с помощью Visual Studio 2015, предназначены для целевой платформы .NET Framework 4.5.2. By default, CLR projects created with Visual Studio 2015 target .NET Framework 4.5.2. Вы можете выбрать .NET Framework 4,6 при создании нового проекта. You can target .NET Framework 4.6 when you create a new project. В диалоговом окне Новый проект измените целевую платформу в раскрывающемся списке в верхней части диалогового окна. In the New Project dialog, change the target framework in the dropdown at the top middle of the dialog. Чтобы изменить целевую платформу для существующего проекта, закройте проект, измените файл проекта ( .vcxproj ) и измените значение целевой версии .NET Framework на 4,6. To change the target framework for an existing project, close the project, edit the project file ( .vcxproj ), and change the value of the Target Framework Version to 4.6. Изменения вступят в силу при следующем открытии проекта. The changes take effect the next time you open the project.

В Visual Studio 2017 целевой .NET Framework по умолчанию является 4.6.1. In Visual Studio 2017, the default target .NET Framework is 4.6.1. Селектор версии платформы находится в нижней части диалогового окна Новый проект . The Framework version selector is at the bottom of the New Project dialog.

Установка поддержки C++/CLI в Visual Studio 2017 Install C++/CLI support in Visual Studio 2017

C++/CLI сам по себе не устанавливается по умолчанию при установке рабочей нагрузки Visual Studio C++. C++/CLI itself isn’t installed by default when you install a Visual Studio C++ workload. Чтобы установить компонент после установки Visual Studio, откройте Visual Studio Installer. To install the component after Visual Studio is installed, open the Visual Studio Installer. Нажмите кнопку изменить рядом с установленной версией Visual Studio. Choose the Modify button next to your installed version of Visual Studio. Перейдите на вкладку установленные компоненты . Прокрутите вниз до раздела компиляторы, средства сборки и среды выполнения и выберите Поддержка C++/CLI. Select the Installed components tab. Scroll down to the Compilers, build tools, and runtimes section, and select C++/CLI support. Выберите изменить , чтобы обновить Visual Studio. Choose Modify to update Visual Studio.

В Visual Studio 2019 целевой платформой по умолчанию для проектов .NET Core является 5,0. In Visual Studio 2019, the default target framework for .NET Core projects is 5.0. Для проектов .NET Frameworks значение по умолчанию — 4.7.2. For .NET Frameworks projects, the default is 4.7.2. Средство выбора версии .NET Framework находится на странице Настройка нового проекта диалогового окна Создание нового проекта . The .NET Framework version selector is on the Configure your new project page of the Create a new project dialog.

Установка поддержки C++/CLI в Visual Studio 2019 Install C++/CLI support in Visual Studio 2019

C++/CLI сам по себе не устанавливается по умолчанию при установке рабочей нагрузки Visual Studio C++. C++/CLI itself isn’t installed by default when you install a Visual Studio C++ workload. Чтобы установить компонент после установки Visual Studio, откройте Visual Studio Installer. To install the component after Visual Studio is installed, open the Visual Studio Installer. Нажмите кнопку изменить рядом с установленной версией Visual Studio. Choose the Modify button next to your installed version of Visual Studio. Перейдите на вкладку установленные компоненты . Прокрутите вниз до раздела компиляторы, средства сборки и среды выполнения и выберите последнюю поддержку C++/CLI для компонента v142 Build Tools . Select the Installed components tab. Scroll down to the Compilers, build tools, and runtimes section, and select the latest C++/CLI support for v142 build tools component. Выберите изменить , чтобы обновить Visual Studio. Choose Modify to update Visual Studio.

Читайте также:  Intel rst premium linux

How to use C++/CLI to program Winforms applications

Is there a pdf or video or some media that can inform me on how to program Winforms with C++. Obviously C++ is the most common programming language and I already have some prior knowledge. But when I try to find media about programming in C++, the examples are usually Console applications. I want some media that can teach me how to program Winforms in C++.

5 Answers 5

Here’s a tutorial showing how to write Windows Forms applications in C++/CLI.

Just be aware that most samples tend to be in C#. Many people purposely use C# for the forms, C++ for their logic, and use C++/CLI to expose their logic as .NET assemblies (For easy use by C#/VB.NET). This helps, since the design-time experience is much nicer in C# or VB.NET for Windows Forms.

Bad idea, IMHO. Managed C++ is ugly; it was never meant to be a garbage-collected language. Its strength lies elsewhere. I recommend C# instead — similar syntax, highly marketable skill.

Preemtive snarky comment: all C++ is ugly.

Have you looked at the MSDN articles? I’m not saying I recommend this, but they do at least give a start.

As far as Seva Alekseyev’s comment that all C++ is ugly: it’s like the old comment about democracy being the worst form of government except for all the others. He’s right that all C++ is ugly, but fails to mention that all the alternatives are even worse.

Just create a new C++ .NET project and start programming your C++. And additional syntax applies to .NET is managed pointers and .NET classes. Information about them you can find in MSDN, including lots of useful examples.

Well, there are opinions all over the place on this topic. My motto is always to use the right size hammer for the job— and, in general, C++ is the wrong size hammer for making winforms. I love C++, but I only use it when there is an absolute necessity for speed of operations.

C# (or VB.Net, if you must) has MUCH better support for UI creation than C++, though I have noticed that Visual Studio 2010 offers some much needed enhancements to make developing Winforms easier in .NET 4.0. If you MUST stick with C++, look into obtaining a beta version of Visual Studio 2010. Otherwise, use C# as your UI, data access, file manipulation, general purpose language and C++ if you have to write a custom physics engine to go with it.

Not the answer you’re looking for? Browse other questions tagged winforms c++-cli or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Строка (C++/CLI и C++/CX) String (C++/CLI and C++/CX)

Среда выполнения Windows и среда CLR представляют строки в виде объектов, управление выделяемой памятью которых осуществляется автоматически. The Windows Runtime and common language runtime represent strings as objects whose allocated memory is managed automatically. Это значит, что в случае выхода строковой переменной за пределы области видимости или завершении работы приложения явно отменять память для строки не требуется. That is, you are not required to explicitly discard the memory for a string when the string variable goes out of scope or your application ends. Чтобы указать, что управление временем существования строкового объекта должно осуществляться автоматически, следует объявить тип string с помощью модификатора дескриптор объекта (^). To indicate that the lifetime of a string object is to be managed automatically, declare the string type with the handle-to-object (^) modifier.

Читайте также:  Улучшаем быстродействие компьютера windows 10

Среда выполнения Windows Windows Runtime

Архитектура среды выполнения Windows требует реализации типа данных String в пространстве имен Platform . The Windows Runtime architecture requires that the String data type be located in the Platform namespace. Для удобства в Visual C++ также предусмотрен тип данных string , являющийся синонимом для Platform::String в пространстве имен default . For your convenience, Visual C++ also provides the string data type, which is a synonym for Platform::String , in the default namespace.

Синтаксис Syntax

Требования Requirements

Параметр компилятора: /ZW Compiler option: /ZW

Среда CLR Common Language Runtime

При компиляции с параметром /clr компилятор преобразует строковые литералы в строки типа String. When compiling with /clr , the compiler will convert string literals to strings of type String. Для сохранения обратной совместимости с существующим кодом у этого правила есть два исключения: To preserve backward compatibility with existing code there are two exceptions to this:

Обработка исключений. Exception handling. Если появляется строковый литерал, компилятор перехватывает его как строковый литерал. When a string literal is thrown, the compiler will catch it as a string literal.

Определение шаблона. Template deduction. Если строковый литерал передается в качестве аргумента шаблона, компилятор не преобразует его в String. When a string literal is passed as a template argument, the compiler will not convert it to a String. Обратите внимание, что строковые литералы, переданные в качестве универсального аргумента, повышаются до String. Note, string literals passed as a generic argument will be promoted to String.

В компиляторе также есть встроенная поддержка трех операторов, которые можно переопределять для настройки их поведения: The compiler also has built-in support for three operators, which you can override to customize their behavior:

System::String^ operator +( System::String, System::String); System::String^ operator +( System::String, System::String);

System::String^ operator +( System::Object, System::String); System::String^ operator +( System::Object, System::String);

System::String^ operator +( System::String, System::Object); System::String^ operator +( System::String, System::Object);

После передачи String компилятор при необходимости упаковывает, а затем объединяет объект (с помощью ToString) со строкой. When passed a String, the compiler will box, if necessary, and then concatenate the object (with ToString) with the string.

Курсор («^») означает, что объявленная переменная является дескриптором управляемого объекта C++/CLI. The caret («^») indicates that the declared variable is a handle to a C++/CLI managed object.

Дополнительные сведения см. в статье Строковые и символьные литералы (C++). For more information see String and Character Literals.

Требования Requirements

Параметр компилятора: /clr Compiler option: /clr

Примеры Examples

В следующем примере кода демонстрируется объединение и сравнение строк. The following code example demonstrates concatenating and comparing strings.

В следующем примере показано, что предоставляемые компилятором операторы можно перегружать, и что компилятор будет искать перегрузку функции на основе типа String. The following sample shows that you can overload the compiler-provided operators, and that the compiler will find a function overload based on the String type.

В следующем примере показано, что компилятор различает собственные строки и строки String. The following sample shows that the compiler distinguishes between native strings and String strings.

Строка (C++/CLI и C++/CX) String (C++/CLI and C++/CX)

Среда выполнения Windows и среда CLR представляют строки в виде объектов, управление выделяемой памятью которых осуществляется автоматически. The Windows Runtime and common language runtime represent strings as objects whose allocated memory is managed automatically. Это значит, что в случае выхода строковой переменной за пределы области видимости или завершении работы приложения явно отменять память для строки не требуется. That is, you are not required to explicitly discard the memory for a string when the string variable goes out of scope or your application ends. Чтобы указать, что управление временем существования строкового объекта должно осуществляться автоматически, следует объявить тип string с помощью модификатора дескриптор объекта (^). To indicate that the lifetime of a string object is to be managed automatically, declare the string type with the handle-to-object (^) modifier.

Читайте также:  Как настроить альт таб windows 10

Среда выполнения Windows Windows Runtime

Архитектура среды выполнения Windows требует реализации типа данных String в пространстве имен Platform . The Windows Runtime architecture requires that the String data type be located in the Platform namespace. Для удобства в Visual C++ также предусмотрен тип данных string , являющийся синонимом для Platform::String в пространстве имен default . For your convenience, Visual C++ also provides the string data type, which is a synonym for Platform::String , in the default namespace.

Синтаксис Syntax

Требования Requirements

Параметр компилятора: /ZW Compiler option: /ZW

Среда CLR Common Language Runtime

При компиляции с параметром /clr компилятор преобразует строковые литералы в строки типа String. When compiling with /clr , the compiler will convert string literals to strings of type String. Для сохранения обратной совместимости с существующим кодом у этого правила есть два исключения: To preserve backward compatibility with existing code there are two exceptions to this:

Обработка исключений. Exception handling. Если появляется строковый литерал, компилятор перехватывает его как строковый литерал. When a string literal is thrown, the compiler will catch it as a string literal.

Определение шаблона. Template deduction. Если строковый литерал передается в качестве аргумента шаблона, компилятор не преобразует его в String. When a string literal is passed as a template argument, the compiler will not convert it to a String. Обратите внимание, что строковые литералы, переданные в качестве универсального аргумента, повышаются до String. Note, string literals passed as a generic argument will be promoted to String.

В компиляторе также есть встроенная поддержка трех операторов, которые можно переопределять для настройки их поведения: The compiler also has built-in support for three operators, which you can override to customize their behavior:

System::String^ operator +( System::String, System::String); System::String^ operator +( System::String, System::String);

System::String^ operator +( System::Object, System::String); System::String^ operator +( System::Object, System::String);

System::String^ operator +( System::String, System::Object); System::String^ operator +( System::String, System::Object);

После передачи String компилятор при необходимости упаковывает, а затем объединяет объект (с помощью ToString) со строкой. When passed a String, the compiler will box, if necessary, and then concatenate the object (with ToString) with the string.

Курсор («^») означает, что объявленная переменная является дескриптором управляемого объекта C++/CLI. The caret («^») indicates that the declared variable is a handle to a C++/CLI managed object.

Дополнительные сведения см. в статье Строковые и символьные литералы (C++). For more information see String and Character Literals.

Требования Requirements

Параметр компилятора: /clr Compiler option: /clr

Примеры Examples

В следующем примере кода демонстрируется объединение и сравнение строк. The following code example demonstrates concatenating and comparing strings.

В следующем примере показано, что предоставляемые компилятором операторы можно перегружать, и что компилятор будет искать перегрузку функции на основе типа String. The following sample shows that you can overload the compiler-provided operators, and that the compiler will find a function overload based on the String type.

В следующем примере показано, что компилятор различает собственные строки и строки String. The following sample shows that the compiler distinguishes between native strings and String strings.

Оцените статью