Форум программистов, компьютерный форум, киберфорум
C++/CLI Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.93/58: Рейтинг темы: голосов - 58, средняя оценка - 4.93
Terra Incognito

Visual Studio 2010 Windows Forms OpenFileDialog

21.03.2011, 12:26. Показов 11070. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте!
Создаю стандартное Windows Forms приложение в Visual Studio 2010. На форму кидаю, допустим, кнопку или текстовое поле.
Теперь я хочу из главного .cpp файла поменять свойства созданной кнопки или заполнить текстбокс. Как получить к ним доступ из этого .cpp файла?
Очень прошу внятный ответ с кодом, пожалуйста. Буду очень благодарен.

Проект: myWFAPP
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//Form1.h
#pragma once
 
namespace myWFAPP {
 
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
 
    /// <summary>
    /// Сводка для Form1
    /// </summary>
    public ref class Form1 : public System::Windows::Forms::Form
    {
    public:
        Form1(void)
        {
            InitializeComponent();
            //
            //TODO: добавьте код конструктора
            //
        }
 
    protected:
        /// <summary>
        /// Освободить все используемые ресурсы.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Button^  button1;
    protected: 
 
    private:
        /// <summary>
        /// Требуется переменная конструктора.
        /// </summary>
        System::ComponentModel::Container ^components;
 
#pragma region Windows Form Designer generated code
        /// <summary>
        /// Обязательный метод для поддержки конструктора - не изменяйте
        /// содержимое данного метода при помощи редактора кода.
        /// </summary>
        void InitializeComponent(void)
        {
            this->button1 = (gcnew System::Windows::Forms::Button());
            this->SuspendLayout();
            // 
            // button1
            // 
            this->button1->Location = System::Drawing::Point(24, 50);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(75, 23);
            this->button1->TabIndex = 0;
            this->button1->Text = L"button1";
            this->button1->UseVisualStyleBackColor = true;
            // 
            // Form1
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(284, 264);
            this->Controls->Add(this->button1);
            this->Name = L"Form1";
            this->Text = L"Form1";
            this->ResumeLayout(false);
 
        }
#pragma endregion
    };
}
Вот основной .cpp

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// myWFAPP.cpp: главный файл проекта.
 
#include "stdafx.h"
#include "Form1.h"
 
using namespace myWFAPP;
 
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    // Включение визуальных эффектов Windows XP до создания каких-либо элементов управления
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false); 
 
    // Создание главного окна и его запуск
    Application::Run(gcnew Form1());
    return 0;
}
Ещё, пожалуйста, киньте ссылку на пример работы с openfiledialog.
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
21.03.2011, 12:26
Ответы с готовыми решениями:

Игра Ping Pong в Windows Forms (Visual Studio 2010)
Приветствую всех кто решил помочь мне с игрой по С++, я должен сделать банальный пинг понг. :-| Суть в том, что макет я сделал как он...

Visual Studio Windows Forms C++
Помогите пожалуйста. Проблема номер 1: При запуске Windows Forms возникает такая ошибка (версия Visual Studio2017) И скорее не...

Как создать Windows Forms в Visual Studio 2013
Как создать Windows Forms в Visual Studio 2013? Я знаю, как это сделать с VS 2012, но мне нужно именно для 2013 (нужно было архив извлечь...

2
Эксперт JavaЭксперт С++
 Аватар для M128K145
8384 / 3617 / 419
Регистрация: 03.07.2009
Сообщений: 10,709
21.03.2011, 14:27
Terra Incognito, вы должны проводить все изменения и вкладывать всю логику в *.h файлах в классах ваших форм. MS со своим CLR так запутали все, что забыли что такое хедер-файл и приходится весь код писать в хедерах.


Пример работы с OpenFileDialog здесь http://msdn.microsoft.com/en-u... .aspx#Y100
0
0 / 0 / 0
Регистрация: 04.02.2016
Сообщений: 4
27.03.2012, 23:24
Подскажите, пожалуйста, как при использовании Windows Forms подключать в файл с функциями заголовочные файлы?

Код пока что практически такой же, как создается в шаблоне, пишу в VC2008 C++:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#pragma once
 
 
namespace test_timer3 {
 
    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>
    /// 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.
    /// </summary>
    public ref class Form1 : public System::Windows::Forms::Form
    {
    public:
        Form1(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }
 
    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Button^  button_start;
    protected: 
 
    private: System::Windows::Forms::Button^  button_stop;
 
    private: System::Windows::Forms::Label^  label1;
    private: System::Windows::Forms::Label^  label_counter;
    private: System::Windows::Forms::Label^  label2;
    private: System::Windows::Forms::Label^  label_result;
    private: System::Windows::Forms::Button^  button_rdtsc;
    private: System::Windows::Forms::Label^  label_tsc;
    private: System::Windows::Forms::Label^  label4;
    protected: 
 
    private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
        System::ComponentModel::Container ^components;
 
#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->button_start = (gcnew System::Windows::Forms::Button());
            this->button_stop = (gcnew System::Windows::Forms::Button());
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->label_counter = (gcnew System::Windows::Forms::Label());
            this->label2 = (gcnew System::Windows::Forms::Label());
            this->label_result = (gcnew System::Windows::Forms::Label());
            this->button_rdtsc = (gcnew System::Windows::Forms::Button());
            this->label_tsc = (gcnew System::Windows::Forms::Label());
            this->label4 = (gcnew System::Windows::Forms::Label());
            this->SuspendLayout();
            // 
            // button_start
            // 
            this->button_start->Location = System::Drawing::Point(34, 36);
            this->button_start->Name = L"button_start";
            this->button_start->Size = System::Drawing::Size(228, 23);
            this->button_start->TabIndex = 0;
            this->button_start->Text = L"Start";
            this->button_start->UseVisualStyleBackColor = true;
            this->button_start->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
            // 
            // button_stop
            // 
            this->button_stop->Location = System::Drawing::Point(34, 81);
            this->button_stop->Name = L"button_stop";
            this->button_stop->Size = System::Drawing::Size(228, 23);
            this->button_stop->TabIndex = 1;
            this->button_stop->Text = L"Stop";
            this->button_stop->UseVisualStyleBackColor = true;
            this->button_stop->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
            // 
            // label1
            // 
            this->label1->AutoSize = true;
            this->label1->Location = System::Drawing::Point(31, 137);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(47, 13);
            this->label1->TabIndex = 2;
            this->label1->Text = L"Counter:";
            // 
            // label_counter
            // 
            this->label_counter->AutoSize = true;
            this->label_counter->Location = System::Drawing::Point(138, 137);
            this->label_counter->Name = L"label_counter";
            this->label_counter->Size = System::Drawing::Size(49, 13);
            this->label_counter->TabIndex = 3;
            this->label_counter->Text = L"00:00:00";
            // 
            // label2
            // 
            this->label2->AutoSize = true;
            this->label2->Location = System::Drawing::Point(31, 177);
            this->label2->Name = L"label2";
            this->label2->Size = System::Drawing::Size(40, 13);
            this->label2->TabIndex = 4;
            this->label2->Text = L"Result:";
            // 
            // label_result
            // 
            this->label_result->AutoSize = true;
            this->label_result->Location = System::Drawing::Point(138, 177);
            this->label_result->Name = L"label_result";
            this->label_result->Size = System::Drawing::Size(49, 13);
            this->label_result->TabIndex = 5;
            this->label_result->Text = L"00:00:00";
            // 
            // button_rdtsc
            // 
            this->button_rdtsc->Location = System::Drawing::Point(34, 220);
            this->button_rdtsc->Name = L"button_rdtsc";
            this->button_rdtsc->Size = System::Drawing::Size(228, 23);
            this->button_rdtsc->TabIndex = 6;
            this->button_rdtsc->Text = L"Read TSC";
            this->button_rdtsc->UseVisualStyleBackColor = true;
            this->button_rdtsc->Click += gcnew System::EventHandler(this, &Form1::button_rdtsc_Click);
            // 
            // label_tsc
            // 
            this->label_tsc->AutoSize = true;
            this->label_tsc->Location = System::Drawing::Point(174, 266);
            this->label_tsc->Name = L"label_tsc";
            this->label_tsc->Size = System::Drawing::Size(13, 13);
            this->label_tsc->TabIndex = 7;
            this->label_tsc->Text = L"0";
            this->label_tsc->TextAlign = System::Drawing::ContentAlignment::MiddleRight;
            // 
            // label4
            // 
            this->label4->AutoSize = true;
            this->label4->Location = System::Drawing::Point(31, 266);
            this->label4->Name = L"label4";
            this->label4->Size = System::Drawing::Size(31, 13);
            this->label4->TabIndex = 8;
            this->label4->Text = L"TSC:";
            // 
            // Form1
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(284, 311);
            this->Controls->Add(this->label4);
            this->Controls->Add(this->label_tsc);
            this->Controls->Add(this->button_rdtsc);
            this->Controls->Add(this->label_result);
            this->Controls->Add(this->label2);
            this->Controls->Add(this->label_counter);
            this->Controls->Add(this->label1);
            this->Controls->Add(this->button_stop);
            this->Controls->Add(this->button_start);
            this->Name = L"Form1";
            this->Text = L"Form1";
            this->ResumeLayout(false);
            this->PerformLayout();
 
        }
#pragma endregion
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e){
                 //button_start->Text = "aaa";
             }
    private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
                 //button_start->Text = "Start";
             }
    private: System::Void button_rdtsc_Click(System::Object^  sender, System::EventArgs^  e) {
                 //unsigned __int64 tsc0;
                 //tsc0 = __rdtsc();
                 //label_tsc->Text = tsc0.ToString();
             }
};
}
Мне надо использовать фунцию rdtsc для реализации секундомера.
В msdn есть пример:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
// rdtsc.cpp
// processor: x86, x64
#include <stdio.h>
#include <intrin.h>
 
#pragma intrinsic(__rdtsc)
 
int main()
{
    unsigned __int64 i;
    i = __rdtsc();
    printf_s("%I64d ticks\n", i);
}
Я пытался вставить
C++
1
2
3
4
#include <stdio.h>
#include <intrin.h>
 
#pragma intrinsic(__rdtsc)
после кода #pragma once, но это не работает
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
27.03.2012, 23:24
Помогаю со студенческими работами здесь

Создание Windows Forms проекта в Visual Studio 2015
Друзья, помогите, не дайте сойти с ума. Присутствует ли какая-то возможность заиметь привычные Windows Forms на VS Community 2015? Меня...

Как создать проект Windows Forms в Visual Studio 2013?
Windows Form есть для С# но нет для C++ или это как то по другому делается?

Сохранение рисунка из chart1. Visual Studio, C++, Windows Forms Application
Как сохранить рисунок графика из chart1. Visual Studio, C++, Windows Forms Application.

простой выбор папки в visual studio для приложения в windows forms
Здравствуйте, товарищи))) спасибо за то, что помогаете!)))) с вашими подсказками написал простенькую прошу для себя, если что позже выложу...

Создание графического приложения (Windows Forms) в Visual Studio
Для последней версии Visual Studio 2013 (всех редакций): Создать проект-&gt;Visual C++-&gt;CLR-&gt;Пустой проект CLR-&gt; После создания проекта...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru