Синтаксическая ошибка идентификатор form1

Im trying to start working with Windows Forms… And I tryed to make programm by lesson… But it doesnt work and I dont understand why. If someone can help me it would be great.

My error:

1>ClCompile:
1>  stdafx.cpp
1>  AssemblyInfo.cpp
1>  Form.cpp
1>Form.cpp(16): error C2872: 'Form1' : ambiguous symbol
1>          could be 'Form1'
1>          or       'c:\users\mizuru\documents\visual studio 2010\projects\form\form\Form1.h(15) : Form1::Form1'
1>Form.cpp(16): error C2061: syntax error : identifier 'Form1'
1>  Generating Code...
1>
1>Build FAILED.

Form.cpp

// Form.cpp : main project file.
    #include "stdafx.h"
    #include "Form1.h"

    using namespace Form1;

    [STAThreadAttribute]
    int main(array<System::String ^> ^args)
    {
        // Enabling Windows XP visual effects before any controls are created
        Application::EnableVisualStyles();
        Application::SetCompatibleTextRenderingDefault(false); 

        // Create the main window and run it
        Application::Run(gcnew Form1());
        return 0;
    }

Form1.h

#pragma once

namespace Form1 {

    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
        using namespace System::Windows::Forms;
        using namespace System::Data;
        using namespace System::Drawing;

        /// <summary>
        /// Summary for Form1
        /// </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^  button1;
        protected: 
        private: System::Windows::Forms::Label^  label1;
        private: System::Windows::Forms::TextBox^  textBox1;

        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->button1 = (gcnew System::Windows::Forms::Button());
                this->label1 = (gcnew System::Windows::Forms::Label());
                this->textBox1 = (gcnew System::Windows::Forms::TextBox());
                this->SuspendLayout();
                // 
                // button1
                // 
                this->button1->Location = System::Drawing::Point(113, 181);
                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;
                this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
                // 
                // label1
                // 
                this->label1->AutoSize = true;
                this->label1->Location = System::Drawing::Point(104, 13);
                this->label1->Name = L"label1";
                this->label1->Size = System::Drawing::Size(35, 13);
                this->label1->TabIndex = 1;


        this->label1->Text = L"label1";
            // 
            // textBox1
            // 
            this->textBox1->Location = System::Drawing::Point(113, 110);
            this->textBox1->Name = L"textBox1";
            this->textBox1->Size = System::Drawing::Size(100, 20);
            this->textBox1->TabIndex = 2;
            this->textBox1->TextChanged += gcnew System::EventHandler(this, &Form1::textBox1_TextChanged);
            // 
            // Form1
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(284, 262);
            this->Controls->Add(this->textBox1);
            this->Controls->Add(this->label1);
            this->Controls->Add(this->button1);
            this->Name = L"Form1";
            this->Text = L"Form1";
            this->ResumeLayout(false);
            this->PerformLayout();

        }
#pragma endregion
    private: System::Void textBox1_TextChanged(System::Object^  sender, System::EventArgs^  e) {
                 label1->Text="";
             }
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
                 label1->Text=textBox1->Text;
             }
    };
}

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
#pragma once
 
//---------------------------------
//--------------------------------
 
 
 
 
namespace Finder {
 
    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>
    /// Сводка для Form2
    /// </summary>
    public ref class Form2 : public System::Windows::Forms::Form
    {
    public:
        Form2(Form1 f1)
        {
            InitializeComponent();
            //
            //TODO: добавьте код конструктора
            //
        }
 
    protected:
        /// <summary>
        /// Освободить все используемые ресурсы.
        /// </summary>
        ~Form2()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::Label^  label1;
    private: System::Windows::Forms::Label^  label2;
    private: System::Windows::Forms::Label^  label3;
    private: System::Windows::Forms::Label^  label4;
    private: System::Windows::Forms::Label^  label5;
    private: System::Windows::Forms::TextBox^  textBox1;
    private: System::Windows::Forms::MaskedTextBox^  maskedTextBox1;
    private: System::Windows::Forms::Label^  label6;
    private: System::Windows::Forms::MaskedTextBox^  maskedTextBox2;
    protected: 
 
    private:
        /// <summary>
        /// Требуется переменная конструктора.
        /// </summary>
        System::ComponentModel::Container ^components;
 
#pragma region Windows Form Designer generated code
        /// <summary>
        /// Обязательный метод для поддержки конструктора - не изменяйте
        /// содержимое данного метода при помощи редактора кода.
        /// </summary>
        void InitializeComponent(void)
        {
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->label2 = (gcnew System::Windows::Forms::Label());
            this->label3 = (gcnew System::Windows::Forms::Label());
            this->label4 = (gcnew System::Windows::Forms::Label());
            this->label5 = (gcnew System::Windows::Forms::Label());
            this->textBox1 = (gcnew System::Windows::Forms::TextBox());
            this->maskedTextBox1 = (gcnew System::Windows::Forms::MaskedTextBox());
            this->label6 = (gcnew System::Windows::Forms::Label());
            this->maskedTextBox2 = (gcnew System::Windows::Forms::MaskedTextBox());
            this->SuspendLayout();
            // 
            // label1
            // 
            this->label1->AutoSize = true;
            this->label1->Location = System::Drawing::Point(12, 9);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(18, 13);
            this->label1->TabIndex = 0;
            this->label1->Text = L"№";
            // 
            // label2
            // 
            this->label2->AutoSize = true;
            this->label2->Location = System::Drawing::Point(59, 9);
            this->label2->Name = L"label2";
            this->label2->Size = System::Drawing::Size(31, 13);
            this->label2->TabIndex = 1;
            this->label2->Text = L"Activ";
            // 
            // label3
            // 
            this->label3->AutoSize = true;
            this->label3->Location = System::Drawing::Point(117, 9);
            this->label3->Name = L"label3";
            this->label3->Size = System::Drawing::Size(70, 13);
            this->label3->TabIndex = 2;
            this->label3->Text = L"Area\\NoArea";
            // 
            // label4
            // 
            this->label4->AutoSize = true;
            this->label4->Location = System::Drawing::Point(286, 9);
            this->label4->Name = L"label4";
            this->label4->Size = System::Drawing::Size(29, 13);
            this->label4->TabIndex = 3;
            this->label4->Text = L"Area";
            // 
            // label5
            // 
            this->label5->AutoSize = true;
            this->label5->Location = System::Drawing::Point(355, 9);
            this->label5->Name = L"label5";
            this->label5->Size = System::Drawing::Size(53, 13);
            this->label5->TabIndex = 4;
            this->label5->Text = L"SubString";
            // 
            // textBox1
            // 
            this->textBox1->Location = System::Drawing::Point(358, 35);
            this->textBox1->Name = L"textBox1";
            this->textBox1->Size = System::Drawing::Size(291, 20);
            this->textBox1->TabIndex = 5;
            this->textBox1->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Form2::textBox1_KeyPress);
            // 
            // maskedTextBox1
            // 
            this->maskedTextBox1->ImeMode = System::Windows::Forms::ImeMode::NoControl;
            this->maskedTextBox1->InsertKeyMode = System::Windows::Forms::InsertKeyMode::Insert;
            this->maskedTextBox1->Location = System::Drawing::Point(289, 35);
            this->maskedTextBox1->Mask = L"[ \\d]\?";
            this->maskedTextBox1->Name = L"maskedTextBox1";
            this->maskedTextBox1->Size = System::Drawing::Size(40, 20);
            this->maskedTextBox1->TabIndex = 7;
            // 
            // label6
            // 
            this->label6->AutoSize = true;
            this->label6->Location = System::Drawing::Point(215, 8);
            this->label6->Name = L"label6";
            this->label6->Size = System::Drawing::Size(48, 13);
            this->label6->TabIndex = 8;
            this->label6->Text = L"Start line";
            // 
            // maskedTextBox2
            // 
            this->maskedTextBox2->Location = System::Drawing::Point(234, 34);
            this->maskedTextBox2->Name = L"maskedTextBox2";
            this->maskedTextBox2->Size = System::Drawing::Size(29, 20);
            this->maskedTextBox2->TabIndex = 9;
            // 
            // Form2
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(741, 380);
            this->Controls->Add(this->maskedTextBox2);
            this->Controls->Add(this->label6);
            this->Controls->Add(this->maskedTextBox1);
            this->Controls->Add(this->textBox1);
            this->Controls->Add(this->label5);
            this->Controls->Add(this->label4);
            this->Controls->Add(this->label3);
            this->Controls->Add(this->label2);
            this->Controls->Add(this->label1);
            this->Name = L"Form2";
            this->Text = L"Form2";
            this->Load += gcnew System::EventHandler(this, &Form2::Form2_Load);
            this->ResumeLayout(false);
            this->PerformLayout();
 
        }
#pragma endregion
    private: System::Void Form2_Load(System::Object^  sender, System::EventArgs^  e)
             {
                // this->textBox1->Text=Find_item[0].substring;
             }
    private: System::Void textBox1_KeyPress(System::Object^  sender, System::Windows::Forms::KeyPressEventArgs^  e) 
             {
                 e->Handled=true;
             }
};
}


Recommended Answers

Take out the .h, that’s the filename, you want to instantiate an object of type Form1. Application::Run(gcnew Form1());

Jump to Post

Did you rename your Form1 class something else?

Jump to Post

The file names are irrelevant. What is you class called?

Jump to Post

All 12 Replies

Member Avatar for jonsca


jonsca

1,059



Quantitative Phrenologist



Team Colleague



Featured Poster



Take out the .h, that’s the filename, you want to instantiate an object of type Form1. Application::Run(gcnew Form1());

Member Avatar for ethanbuckley


I still get the same error by removing the .h extension

Member Avatar for jonsca


jonsca

1,059



Quantitative Phrenologist



Team Colleague



Featured Poster



Did you rename your Form1 class something else?

Member Avatar for ethanbuckley


its Form1.h, they are both the same… would it have anything to do with one of the other errors? this is the only error relating to the form1.cpp where as the 25 others relate to form1.h

another note, my form1.cpp is actually called WaveMachine.cpp, the reference appears to have been the same so I cannot believe that changing the .cpp name to form1 would be the issue

Edited

by ethanbuckley because:

n/a

Member Avatar for Narue


Narue

5,707



Bad Cop



Team Colleague



The file names are irrelevant. What is you class called?

Edited

by Narue because:

n/a

Member Avatar for jonsca


jonsca

1,059



Quantitative Phrenologist



Team Colleague



Featured Poster



Which other errors?

There is no form1.cpp (unless you specifically created a file with that title), so that shouldn’t matter.

The IDE should have autogenerated the code you posted above, that’s why having the .h there was suspect.

There should be a line in your form1.h that says something like public ref class Form1 : public System::Windows::Forms::Form Check and make sure it says Form1 there.

Edited

by jonsca because:

here there and everywhere

Member Avatar for ethanbuckley


Sorry to be a pain, im beginner

I have three header files,
AddWaveTrack_form1.h
EditWaveTrack_form1.h
Form1.h (25 Errors)

And then I have my Source Files,
AddWaveTrack_form1.cpp
EditWaveTrack_form1.cpp
WaveMachine.cpp (1 Error aka this one)

Member Avatar for ethanbuckley


Ok so I found:

public ref class Form1 : public System::Windows::Forms::Form

added a 1 onto the form at the end, this generated 50 errors one of them being:

Error 1 error C2039: ‘Form1’ : is not a member of ‘System::Windows::Forms’ c:\users\black chocobo\desktop\wavemachine\managesongs\wavemachine\wavemachine\wavemachine\Form1.h 29

does it require .h? UPDATED no change 1 extra error

Edited

by ethanbuckley because:

n/a

Member Avatar for ethanbuckley


the start of my form1.h goes like this:

#pragma once


#include "AddWaveTrack_form1.h"
#include "EditWaveTrack_form1.h"

namespace WaveMachine {

	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;

	using namespace System::Media;

	/// <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
	{

Edited

by ethanbuckley because:

n/a

Member Avatar for jonsca


jonsca

1,059



Quantitative Phrenologist



Team Colleague



Featured Poster



So, your WaveMachine.cpp file should look something like this:

// WaveMachine.cpp : main project file.

#include "stdafx.h"
#include "Form1.h"

using namespace WaveMachine; //is this line intact?

[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
	// Enabling Windows XP visual effects before any controls are created
	Application::EnableVisualStyles();
	Application::SetCompatibleTextRenderingDefault(false); 

	// Create the main window and run it
	Application::Run(gcnew Form1());
	return 0;
}

Edited

by jonsca because:

n/a

Member Avatar for ethanbuckley


that is correct mine is exactly the same…

Member Avatar for jonsca


jonsca

1,059



Quantitative Phrenologist



Team Colleague



Featured Poster



I don’t know what it is then. See what happens once you’ve corrected the other errors.


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.


Форум программистов Vingrad

Модераторы: Partizan, gambit

Страницы: (2) Все 1 [2] 
( Перейти к первому непрочитанному сообщению )

Поиск:

Ответ в темуСоздание новой темы
Создание опроса
> Работа с графикой в Windows Forms. Независимо-передвигающиеся круги.  

V

   

Опции темы

Pork6
Дата 26.10.2009, 15:49 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Новичок

Профиль
Группа: Участник
Сообщений: 34
Регистрация: 21.12.2006
Где: Санкт-Петербург

Репутация: нет
Всего: нет

Нет, с Krug-ом все верно. Структура такая:

Код

public class Krug
    {
        //...
    };

public ref class Form1 : public System::Windows::Forms::Form
    {
        //...
        static List<Krug^>^ circles = gcnew List<Krug^>(); // 4 ошибки
        //...
    };

error C3699: ^: это косвенное обращение невозможно использовать для типа «testCLR::Krug»

error C3225: аргумент универсального типа для «T» не может быть «testCLR::Krug *», он должен являться типом значения или дескриптором ссылочного типа

(повторяются дважды на строчке с объявлением List-а)

Без static-а Си ругается, так что тоже добавил.

Это сообщение отредактировал(а) Pork6 — 26.10.2009, 15:50

PM MAIL WWW ICQ Skype   Вверх
KelTron
Дата 26.10.2009, 17:22 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Опытный
**

Профиль
Группа: Участник
Сообщений: 745
Регистрация: 8.10.2006
Где: Красноярск

Репутация: 11
Всего: 38

Тогда наверно так:

Код

public ref class Krug
    {
        //...
    };

И static  не нужно делать, просто код создания списка помести в конструктор.

Код

Form1(void)
{
    InitializeComponent();
    this->circles = gcnew List<Krug^>();

}

Глядишь я такими темпами C++.NET выучу, пока с этим примером разбираюсь))

Это сообщение отредактировал(а) KelTron — 26.10.2009, 17:40

———————

Тысячами незримых нитей обвивает тебя Закон. Разрубишь одну — преступник. Десять — смертник. Все — Бог.
Эвенгар Салладорский, основатель Школы Тьмы.

PM MAIL   Вверх
Pork6
Дата 26.10.2009, 18:50 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Новичок

Профиль
Группа: Участник
Сообщений: 34
Регистрация: 21.12.2006
Где: Санкт-Петербург

Репутация: нет
Всего: нет

Я тоже надеюсь, что выучу )

Что бы он нормально Krug подцепил, пришлось его в отдельный h-файл, с прописыванием оного в главном файле:

Код

#include "Krug.h"

И теперь последний штрих остался — это создание самих кругов. Написал вот так:

Код

this->circles->Add(gcnew Krug(0, 0, 10) {OffsetX = 2, OffsetY = 3});

И получил ошибки:

error C2065: OffsetX: необъявленный идентификатор    
error C2552: $S6: инициализация не агрегированных данных с помощью списка инициализации не допускается
error C2065: OffsetY: необъявленный идентификатор    
error C2078: слишком много инициализаторов

Насколько я понял, ему не нравится синтаксис, а именно — наличие и/или содержимое фигурных скобок. 

Честно пытался найти справку по использовании класса в Add, но не нашел ничего.

По этому поводу есть идеи?

В любом случае, спасибо )

PM MAIL WWW ICQ Skype   Вверх
KelTron
Дата 26.10.2009, 19:06 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Опытный
**

Профиль
Группа: Участник
Сообщений: 745
Регистрация: 8.10.2006
Где: Красноярск

Репутация: 11
Всего: 38

Ну вообще это синтаксический сахар C#. Надо просто на старый лад переделать.

Код

Krug^ krug = gcnew Krug(0, 0, 10);
krug->OffsetX = 2;
krug->OffsetY = 3;
this->circles->Add(krug);

Это сообщение отредактировал(а) KelTron — 26.10.2009, 19:07

———————

Тысячами незримых нитей обвивает тебя Закон. Разрубишь одну — преступник. Десять — смертник. Все — Бог.
Эвенгар Салладорский, основатель Школы Тьмы.

PM MAIL   Вверх
Pork6
Дата 26.10.2009, 20:49 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Новичок

Профиль
Группа: Участник
Сообщений: 34
Регистрация: 21.12.2006
Где: Санкт-Петербург

Репутация: нет
Всего: нет

Сейчас появилась проблема с классом Krug. Он не видит bounds из Form1 (главной формы).

Сделал, как надо, в Krug.h прописал 

Код

#include "Form1.h" 

и создал экземпляр формы для работы с ней: 

Код

Form1^ form = gcnew Form1(); //ошибки

Но получаю:
error C2065: form: необъявленный идентификатор
error C2061: синтаксическая ошибка: идентификатор «Form1»

Все это я делаю для функции Draw, которая должна принимать этот bounds из Form1.

Многострадальный проект в комплекте.

Присоединённый файл ( Кол-во скачиваний: 6 )

Присоединённый файл
 testCLR.rar 742,53 Kb

PM MAIL WWW ICQ Skype   Вверх
KelTron
Дата 26.10.2009, 21:55 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Опытный
**

Профиль
Группа: Участник
Сообщений: 745
Регистрация: 8.10.2006
Где: Красноярск

Репутация: 11
Всего: 38

Копец…такое ощущение, что ты уже наугад код пишешь.

Разве сложно по аналогии с шарпом преобразовать? Я думал может у тебя будет пара вопросов, а так получается на каждой строчке спотыкаешься, видимо проще было сразу на С++.NET написать, хотя я его не знаю. Учись искать информацию.

Короче вот, возьми это и сравни с тем примером, что я давал в самом начале. Это должно решить все твои проблемы..)

Присоединённый файл ( Кол-во скачиваний: 10 )

Присоединённый файл
 testCLR.rar 79,67 Kb

———————

Тысячами незримых нитей обвивает тебя Закон. Разрубишь одну — преступник. Десять — смертник. Все — Бог.
Эвенгар Салладорский, основатель Школы Тьмы.

PM MAIL   Вверх
Pork6
Дата 26.10.2009, 23:21 (ссылка)
| (нет голосов)
Загрузка ... Загрузка …




Быстрая цитата

Цитата

Новичок

Профиль
Группа: Участник
Сообщений: 34
Регистрация: 21.12.2006
Где: Санкт-Петербург

Репутация: нет
Всего: нет

Получилось, что сложно. Может я ищу информацию как-то не правильно? MSDN, Google, CodeNet… 

Еще раз большое спасибо за помощь. Во всем разобрался, буду внедрять. 

PM MAIL WWW ICQ Skype   Вверх



















Страницы: (2) Все 1 [2] 

Ответ в темуСоздание новой темы
Создание опроса
Прежде чем создать тему, посмотрите сюда:

Partizan

PashaPash

  • Что же такое .NET? Краткое описание, изучаем.
  • Какой язык программирования выбрать? выбираем.
  • C#. С чего начать? начинаем.
  • Защита исходного кода .NET приложений, защищаем.
  • Литература по .NET, обращаемся.

  • FAQ раздела, ищем здесь.
  • Архиполезные ссылки: www.connectionstrings.com, www.pinvoke.net, www.codeproject.com

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс «транслит» если у Вас нет русских шрифтов.

Что делать если Вам помогли, но отблагодарить помощника плюсом в репутацию Вы не можете(не хватает сообщений)?
Пишите сюда, или отправляйте репорт. Поставим :)

Так же не забывайте отмечать свой вопрос решенным, если он таковым является :)


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.DUDA, Partizan, PashaPash.

 

0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | .NET для новичков | Следующая тема »
  • Remove From My Forums
  • Question

  • Hi guys,

    I need your help. I am using managed c++ and I have no idea how to correct the errors I have received on my error list.

    Here it’s the error with the each line of the code:

    Error: [B]syntax error : identifier ‘MENUITEMINFO'[/B]
    Code: [CODE]static int GetMenuItemInfo(IntPtr hMenu, int uItem, bool fByPosition, MENUITEMINFO %lpmii);[/CODE]

    Error: [B]syntax error : identifier ‘_'[/B]
    Error: [B]error C2238: unexpected token(s) preceding ‘;'[/B]
    Code: [CODE][StructLayout(LayoutKind::Sequential, CharSet=CharSet::Auto), StructLayout(LayoutKind::Sequential, CharSet=CharSet::Auto)]_;[/CODE]

    Error: [B]error C3379: ‘Project1::Options1::MENUITEMINFO’ : a nested class cannot have an assembly access specifier as part of its declaration[/B]
    Code: [CODE]public value class MENUITEMINFO {
        public:
            int cbSize;
            int fMask;
            int fType;
            int fState;
            int wID;
            int hSubMenu;
            int hbmpChecked;
            int hbmpUnchecked;
            int dwItemData;
            String ^dwTypeData;
            int cch;
        };[/CODE]

    Error: [B]error C2039: ‘arrow_black’ : is not a member of ‘System::Windows::Forms::Control::Properties'[/B]

    [B]error C2065: ‘arrow_black’ : undeclared identifier[/B]

    Code: [CODE]PictureBox1->Image = Properties::arrow_black; [/CODE]

    Error: [B]error C2664: ‘void Microsoft::Win32::RegistryKey::SetValue(System::String ^,System::Object ^,Microsoft::Win32::RegistryValueKind)’ : cannot convert parameter 3 from ‘bool’ to ‘Microsoft::Win32::RegistryValueKind'[/B]
    Code: [CODE]Registry::LocalMachine->CreateSubKey(«SOFTWARE\\MyApp\\TrayEnabled»)->SetValue(«Enabled», «False», this->NotifyIcon1->Visible == true);[/CODE]

    Error: [B]error C2653: ‘My’ : is not a class or namespace name[/B]
    Code: [CODE]int screenX = My::Computer::Screen::Bounds.Height;
                 int screenY = My::Computer::Screen::Bounds.Width;[/CODE]

    Error: [B]error C2228: left of ‘.OpenSubKey’ must have class/struct/union[/B]
    Error: [B]error C2227: left of ‘->SetValue’ must point to class/struct/union/generic type[/B]
    Code: [CODE]Microsoft::Win32::Registry::LocalMachine.OpenSubKey(«Software\\Microsoft\\Windows\\CurrentVersion\\Run», true)->SetValue(«MyApp», Application::ExecutablePath);[/CODE]

    Could you please me as I needs to make changes to correct the errors with above codes?

    Any advice would be much appreciate.

    Thanks!

Answers

  • Hello,

    >Error: [B]syntax error : identifier ‘MENUITEMINFO'[/B]
    >Code: [CODE]static int GetMenuItemInfo(IntPtr hMenu, int uItem, bool fByPosition, MENUITEMINFO %lpmii);[/CODE]

    Have you defined the “MENUITEMINFO” structure before the code? If you have defined after, you may use a forward declaration before this
    line to compile the code.

    >Error: [B]syntax error : identifier ‘_'[/B]
    >Error: [B]error C2238: unexpected token(s) preceding ‘;'[/B]
    >Code: [CODE][StructLayout(LayoutKind::Sequential, CharSet=CharSet::Auto), StructLayout(LayoutKind::Sequential, CharSet=CharSet::Auto)]_;[/CODE]

    You have the unwanted extra symbol “_” before “;”

    >Error: [B]error C3379: ‘Project1::Options1::MENUITEMINFO’ : a nested class cannot have an assembly access specifier as part of its declaration[/B]
    >Code: [CODE]public value class MENUITEMINFO {
    >public:
    >int cbSize;
    >int fMask;
    >int fType;
    >int fState;
    >int wID;
    >int hSubMenu;
    >int hbmpChecked;
    >int hbmpUnchecked;
    >int dwItemData;
    >String ^dwTypeData;
    >int cch;
    >};[/CODE]

    Remove the “public” specifier.

    MENUITEMINFO is a native structure for menu which is defined in winuser.h (include Windows.h).
     In Managed C++, you don’t have to create a wrapper structure and do the P/Invoke as C# or VB, you can direct call the native api’s after include the “Windows.h”.

    >Error: [B]error C2039: ‘arrow_black’ : is not a member of ‘System::Windows::Forms::Control::Properties'[/B]

    >[B]error C2065: ‘arrow_black’ : undeclared identifier[/B]

    >Code: [CODE]PictureBox1->Image = Properties::arrow_black; [/CODE]

    There is no arrow_black defined in ‘System::Windows::Forms::Control::Properties’. If you want to load an image from a file, a GDI handler or stream,
    please use
    System::Drawing::image.   

    >Error: [B]error C2664: ‘void Microsoft::Win32::RegistryKey::SetValue(System::String ^,System::Object ^,Microsoft::Win32::RegistryValueKind)’ : cannot convert parameter 3 from ‘bool’ to ‘Microsoft::Win32::RegistryValueKind'[/B]
    >Code: [CODE]Registry::LocalMachine->CreateSubKey(«SOFTWARE\\MyApp\\TrayEnabled»)->SetValue(«Enabled», «False», this->NotifyIcon1->Visible == true);[/CODE]

    The third parameter of RegistryKey::SetValue is

    RegistryValueKind Enumeration which specifies the data types to use when storing values in the registry, or identifies the data type of a value in the registry. In your code, “this->NotifyIcon1->Visible ==
    true” is a bool value but not a value kind. Please make sure what is register key value kind for the key you are set. For example if the key’s type is a DWord, fill the third parameter as RegistryValueKind::DWord.

    >Error: [B]error C2653: ‘My’ : is not a class or namespace name[/B]
    >Code: [CODE]int screenX = My::Computer::Screen::Bounds.Height;
    >int screenY = My::Computer::Screen::Bounds.Width;[/CODE]

    Have you defined a class or namespace called “MY”? Please double check the code.

    >Error: [B]error C2228: left of ‘.OpenSubKey’ must have class/struct/union[/B]
    >Error: [B]error C2227: left of ‘->SetValue’ must point to class/struct/union/generic type[/B]
    >Code: [CODE]Microsoft::Win32::Registry::LocalMachine.OpenSubKey(«Software\\Microsoft\\Windows\\CurrentVersion\\Run», true)->SetValue(«MyApp», Application::ExecutablePath);[/CODE]

    Change the
    LocalMachine.OpenSubKey to LocalMachine::OpenSubKey. you are calling a static method of Microsoft::Win32::Registry.

    If you have any concern, please let me know.

    Cheers,

    Yi


    Yi Feng Li [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by

      Tuesday, April 12, 2011 3:08 PM

  • >error C3845: ‘Project1::Options1::myindexes’: only static
    >data members can be initialized inside a ref class or value
    >type

    Have you taken the time to look up that error in the compiler’s
    help — either locally or online? It should make clear what
    you’re doing wrong.

    It’s difficult for anyone to give exact solutions to some
    of your errors as there is no context for the single lines
    of code which you are posting. Often the code lines you
    show would be valid in one context but invalid in another.

    e.g. —

    Valid:

    int main(array<System::String ^> ^args)
    {
      System::Collections::Generic::List<int> ^myindexes =
        gcnew System::Collections::Generic::List<int>();
      return 0;
    }

    Invalid:

    ref class A {
    public:
      // C3845 error
      System::Collections::Generic::List<int> ^myindexes =
        gcnew System::Collections::Generic::List<int>();
    };

    Valid:

    ref class A {
    public:
      static System::Collections::Generic::List<int> ^myindexes =
        gcnew System::Collections::Generic::List<int>();
    };

    Valid:

    ref class A {
    public:
      A();
      System::Collections::Generic::List<int> ^myindexes;
    };

    A::A()
    {
      myindexes = gcnew System::Collections::Generic::List<int>();
    }

    — Wayne

    • Marked as answer by
      Yi Feng Li
      Tuesday, April 12, 2011 3:08 PM

  • Hi Mark,

    >>System::Collections::Generic::List<int> ^myindexes = gcnew System::Collections::Generic::List<int>();

    >>error C3845: ‘Project1::Options1::myindexes’: only static data members can be initialized inside a ref class or value type

    You cannot initialized a non-static type inside a ref class, please define it as static or initialize it in a constructer. E.g.

    ref class myclass

    {

       
    //System::Collections::Generic::List<int> ^myindexes = gcnew System::Collections::Generic::List<int>(); //C3845

       
    //static System::Collections::Generic::List<int> ^myindexes = gcnew System::Collections::Generic::List<int>();

       
    System::Collections::Generic::List<int> ^myindexes;

       
    myclass()

       
    {

        
    myindexes = gcnew System::Collections::Generic::List<int>();

       
    }

    };

    >>error C3094: ‘System::Runtime::InteropServices::StructLayoutAttribute’: anonymous usage not allowed

    An attribute was not scoped correctly. For more information, see
    User-Defined Attributes.

    >>error C2143: syntax error : missing ‘;’ before ‘using’

    Double check if you miss a “;” at the end of some class.

    String^ URL = «http://www.mysite.com/myscript.php?user=» + Form2::ComboBox1::Text & «&pass=» + Form2::TextBox1::Text;

    error C2597: illegal reference to non-static member ‘System::Windows::Forms::Form::Text’

    error C2568: ‘+’ : unable to resolve function overload

    To access the some control inside form, you need to use “->” but not “::”. Normally, “::” is for accessing namespace
    or static member.

    >>And how I can add the images in the application and use the properties to extract the images from the application?

    You can use
    System::Drawing::Image class’s static method
    Image::FromFile to create an image from the specified file.

    I’m not clear about what you mean “use the properties to extract the images from the application?”, could you explain it a little
    bit more?

    Cheers,

    Yi


    Yi Feng Li [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by
      Yi Feng Li
      Tuesday, April 12, 2011 3:09 PM

  • Hello,

    Hello,

    >Should I have to change from this:

    >System::Collections::Generic::List<int> ^myindexes = gcnew System::Collections::Generic::List<int>();

    It depends on your code. From the information provided, the error shows you initialize the myindexes inside the definition of a class.
    If so, you have to either define it as static or initialize it in a function, e.g. constructer.

    And could you also help me please to correct the errors as I am still getting. I don’t know what to do with it.

    There are too many errors. Actually, you can find all the reference of the error message form MSDN library, the error message tell you
    what is exactly problem you have.  I will provide some comments here based on your error message.

    >error C2061: syntax error : identifier ‘MENUITEMINFO’

    C2061: The compiler found an identifier where it wasn’t expected. Make sure that identifier is declared before you use it. See my first
    post.

    >sValue = safe_cast<String>(oRegKey->GetValue(«Proxy»));

    >error C2682: cannot use ‘safe_cast’ to convert from ‘System::Object ^’ to ‘System::String’

    >error C2440: ‘=’ : cannot convert from ‘System::String’ to ‘System::String ^’

    Try safe_cast<String^>.

    >if (GetHTMLPage(«http://www.whatismyip.com» + ProxyIP->Text, AutomaticCheckbox->Checked, Address->Text, ((Microsoft::VisualBasic::Information::IsNumeric(Ports->Text))

    >error C3083: ‘Information’: the symbol to the left of a ‘::’ must be a type

    >error C2039: ‘IsNumeric’ : is not a member of ‘Microsoft::VisualBasic’

    >error C2446: ‘:’ : no conversion from ‘int’ to ‘System::String ^’

    >error C3861: ‘IsNumeric’: identifier not found

    >Microsoft::VisualBasic::Interaction(Application::ProductName, «Settings», «Address», Address->Text);

    >error C2039: ‘Interaction’ : is not a member of ‘Microsoft::VisualBasic’

    Please double check if you have add the Microsoft.VisualBasic assembly in project properties pages.

    The rest of errors, without code, it is hard to offer the solution for you. However, it is not really hard to fix the error you have
    after get meaning of each error code. More information about how to get help on a particular error message, please check
    http://msdn.microsoft.com/en-us/library/8x5x43k7.aspx .

    >>Most of the errors I am getting are the images, so I would like to add the images in my application resources, but I don’t know
    how to use the properties to read the images from the resources.

    In VC++ /CLI you need to create a Resource Manager object to load the objects from the resource file. Here is the example: suppose the
    application is called MyApplication and resource file is Form1.resx. In the form, we have created an image resource called Image1 and we use a Picture box control (picturebox1) to show the image. the code is look like following:

    System::Resources::ResourceManager^ resources =

                        
    gcnew System::Resources::ResourceManager(«MyApplication.Form1», System::Reflection::Assembly::GetExecutingAssembly() );

               
    this->pictureBox1->Image =

                   
    cli::safe_cast<System::Drawing::Image^>(resources->GetObject(«Image1»));

    Hope the information helps.

    YI


    Yi Feng Li [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by
      Yi Feng Li
      Tuesday, April 12, 2011 3:09 PM

  • >Don’t tell me that if I should buy a book or do a research.

    That was Yi’s advice, not mine. But I agree 100%.

    >These requirements would not help me to get anywhere, the
    >forums are the only place to go.

    Are you saying that if these forums didn’t exist you wouldn’t
    be able to complete a program? Forums and newsgroups exist to
    help solve problems which lend themselves to relatively brief
    answers. They are *not* a substitute for in-depth learning
    which can only come from concentrated study via books, courses
    or tutorials. Even the experts and gurus acquired much of their
    knowledge that way, plus studying the documentation and praxis.

    With respect to your long list of errors, you should be aware
    that it often happens that one error in the code spawns a
    plethora of error messages. The compiler’s parser can lose
    its way and start spewing out messages because it’s lost
    its way. That’s why it’s usually a good idea to attack the
    first errors and see if the others go away or change. Looking
    for others to give you definitive answers to all of the messages
    from a single compile is unrealistic.

    >String ^six = «6.»;

    >if (six = a->Length < 2 || String::IsNullOrEmpty(a[2]))

    >Errors: error C2440: ‘=’ : cannot convert from ‘bool’ to
    >’System::String ^’  <—— the error are highlighting on
    >if six statement.

    What exactly are you trying to do with this statement?

    >if (six = a->Length < 2 …

    Why are you *assigning* something to «six» here?

    The error is telling you that the expression
    a->Length < 2
    returns either true or false (a bool). But variable «six»
    is a String object. So you can’t do that assignment. You
    can’t store a bool into a String.

    Rethink what you’re trying to do and fix your code.

    — Wayne

    • Marked as answer by
      Yi Feng Li
      Tuesday, April 12, 2011 3:09 PM

  • Hello,

    >>Error: error C2248: ‘MyApplication1::Form1::MENUITEMINFO’ : cannot access private class declared

    Make sure the class MENUITEMINFO is defined as public and can be access by the GetMenuItemInfo function. E.g.

    public ref class MENUITEMINFO {

       
    public:

           
    int cbSize;

           
    int fMask;

           
    int fType;

           
    int fState;

           
    int wID;

           
    int hSubMenu;

           
    int hbmpChecked;

           
    int hbmpUnchecked;

           
    int dwItemData;

           
    String ^dwTypeData;

           
    int cch;

       
    };

     [System::Runtime::InteropServices::DllImport(«user32″, EntryPoint=»GetMenuItemInfo», ExactSpelling=false, CharSet=System::Runtime::InteropServices::CharSet::Auto,
    SetLastError=true)]

     static int GetMenuItemInfo(IntPtr hMenu, int uItem, bool fByPosition, MENUITEMINFO ^%lpmii);

    >>Errors: error C2440: ‘=’ : cannot convert from ‘bool’ to ‘System::String ^’ <—— the error are highlighting on if six statement.

    six = a->Length < 2 means you are assigning a Boolean value to a string, which is not valid. For the if statement, it requires the Boolean value. Do you want
    to handle the following condition? the length of the string six equals a->length and a->length is less than 2 or String::IsNullOrEmpty(a[2]), if so, the if statement should looks like if(six->Length == a->Length && a->Length <2 ||
    String::IsNullOrEmpty(a[2])).  

    >>Errors: error C2146: syntax error : missing ‘;’ before identifier ‘get’ <—— the error are highlight on msgboxresult get; statement.

    >>Errors: error C4430: missing type specifier — int assumed. Note: C++ does not support default-int <——- same line as above

    >>Error: error C3900: ‘MyApplication1::Form1::QuitMe::MsgBoxResult’: not allowed in current scope <——- same line as above

    >>Error 71 error C2059: syntax error : ‘{‘ <——— the error are hightlight on ‘{‘ just after the msgboxresult get;

    >>Error: error C2334: unexpected token(s) preceding ‘{‘; skipping apparent function body <—— same as above

    >>Error: error C2061: syntax error : identifier ‘MsgBoxResult’ <——— the error are highlight on MsgBoxResult value statement.

    >>Error: error C3904: ‘MyApplication1::Form1::QuitMe::set’: must specify 1 parameter(s) <—— same as above

    >>Error: error C3903: ‘MyApplication1::Form1::QuitMe’: does not have set or get method <——— the error are highlight on ‘}’ at the end of the statement.

    The following is the modified code:

    public:

     
    Microsoft::VisualBasic::MsgBoxResult m_Result;

     
    property Microsoft::VisualBasic::MsgBoxResult QuitMe

     
    {

       
    Microsoft::VisualBasic::MsgBoxResult get()

       
    {

         
    return m_Result;

       
    }

       
    void set(Microsoft::VisualBasic::MsgBoxResult value)

       
    {

         
    m_Result = value;

       
    }

     
    }

    >>Errors: error C2664: ‘void System::Windows::Forms::Control::Text::set(System::String ^)’ : cannot convert parameter 1 from ‘int’ to ‘System::String ^’ <—-
    the error are highlighting on if GetHTMLPage statement.

    This message shows you are pass a integer to a function which requires a String. I think the problem statement is ProxyPorts->Text = 0. If you want to pass a
    empty string, try “” or nullptr.

    >>Error: error C2065: ‘Form1’ : undeclared identifier <—— The error are highlighting on Form1^ form1 statement.

    >>Error: error C2065: ‘form1’ : undeclared identifier <—— same as above

    >>Error: error C2061: syntax error : identifier ‘Form1’ <—— same as above

    >>Error: error C2227: left of ‘->LANG_Arabic’ must point to class/struct/union/generic type <—— the error are highlighting on if form1 statement.

    >>Error: error C2227: left of ‘->Checked’ must point to class/struct/union/generic type <—— same as above.

    Do you forget to include form1.h file in a class where you want to use Form1?
      

    Cheers,

    Yi


    Yi Feng Li [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by
      Yi Feng Li
      Tuesday, April 12, 2011 3:09 PM

Понравилась статья? Поделить с друзьями:
  • Синтаксическая ошибка неожиданный символ после символа продолжения строки
  • Синтаксическая ошибка и настройкагруппировкиобщейнастройки этодействующийпараметр
  • Синтаксическая ошибка неожиданный конец файла bash
  • Синтаксическая ошибка выбрать во вложенном запросе
  • Синтаксическая и пунктуационная ошибка