I have two related qestions on the code included below
1) I am trying to read from a serial port that is part of a Visual C++ Form. I want to create a thread in the InitializeComponent function but I get this error on the form page when I include the call to start the thread:
"Warning 1 Could not find type 'Thread'. Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built."
2) The thread will run in the static function Read. Read needs to resolve the serial port that is in the main form (serial port is named arduino),
but it apparently can't resolve them: "left of .ReadLine' must have class/struct/union"
Suggestions?
using namespace System::IO::Ports;
using namespace System::Threading;
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
private: void static Read(void)
{
while (1)
{
try
{
String^ message = arduino.ReadLine();
// this->ArduinoOutputTextBox->Text = message;
}
catch (TimeoutException ^) { }
}
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ USB_button;
private: System::IO::Ports::SerialPort^ arduino;
private: System::Windows::Forms::TextBox^ ArduinoOutputTextBox;
private: System::ComponentModel::IContainer^ components;
protected:
private:
/// <summary>
/// Required designer variable.
/// </summary>
#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)
{
Thread^ readThread = gcnew Thread(gcnew ThreadStart(Read));
this->components = (gcnew System::ComponentModel::Container());
this->USB_button = (gcnew System::Windows::Forms::Button());
this->arduino = (gcnew System::IO::Ports::SerialPort(this->components));
this->ArduinoOutputTextBox = (gcnew System::Windows::Forms::TextBox());
this->SuspendLayout();
arduino is a reference to an object, not an actual object.
You ned to write arduino->readLine().
Related
So i've been trying to process audio using JUCE and followed a tutorial and there he used override on one of the functions but when i do it it says "Expected function body after function declarator". The goal is to play random white noise as explained by the video.
Video link: https://www.youtube.com/watch?v=GjNeYI6-uNE&index=11&list=PLLgJJsrdwhPxa6-02-CeHW8ocwSwl2jnu
Code:
/*
==============================================================================
This file was auto-generated!
==============================================================================
*/
#include "MainComponent.h"
//==============================================================================
MainComponent::MainComponent()
{
// Make sure you set the size of the component after
// you add any child components.
setSize (800, 600);
// specify the number of input and output channels that we want to open
setAudioChannels (2, 2);
}
MainComponent::~MainComponent()
{
// This shuts down the audio device and clears the audio source.
shutdownAudio();
}
//==============================================================================
void MainComponent::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
{
// This function will be called when the audio device is started, or when
// its settings (i.e. sample rate, block size, etc) are changed.
// You can use this function to initialise any resources you might need,
// but be careful - it will be called on the audio thread, not the GUI thread.
// For more details, see the help for AudioProcessor::prepareToPlay()
}
void MainComponent::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override /*this one gets the error*/
{
for (int channel = 0; channel < bufferToFill.buffer->getNumChannels(); ++channel)
{
float* const buffer = bufferToFill.buffer->getWritePointer(channel, bufferToFill.startSample);
for (int sample = 0; sample < bufferToFill.numSamples; ++sample)
{
buffer[sample] = (random.nextFloat() * 2.0f - 1.0f) * 0.25;
}
}
bufferToFill.clearActiveBufferRegion();
}
void MainComponent::releaseResources()
{
// This will be called when the audio device stops, or when it is being
// restarted due to a setting change.
// For more details, see the help for AudioProcessor::releaseResources()
}
//==============================================================================
void MainComponent::paint (Graphics& g)
{
// (Our component is opaque, so we must completely fill the background with a solid colour)
g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));
// You can add your drawing code here!
}
void MainComponent::resized()
{
// This is called when the MainContentComponent is resized.
// If you add any child components, this is where you should
// update their positions.
}
.h file:
/*
==============================================================================
This file was auto-generated!
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
//==============================================================================
/*
This component lives inside our window, and this is where you should put all
your controls and content.
*/
class MainComponent : public AudioAppComponent
{
public:
//==============================================================================
MainComponent();
~MainComponent();
//==============================================================================
void prepareToPlay (int samplesPerBlockExpected, double sampleRate) override;
void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override;
void releaseResources() override;
//==============================================================================
void paint (Graphics& g) override;
void resized() override;
private:
//==============================================================================
// Your private member variables go here...
Random random;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainComponent)
};
Main.cpp
/*
==============================================================================
This file was auto-generated!
It contains the basic startup code for a JUCE application.
==============================================================================
*/
#include "../JuceLibraryCode/JuceHeader.h"
#include "MainComponent.h"
//==============================================================================
class AudioOutApplication : public JUCEApplication
{
public:
//==============================================================================
AudioOutApplication() {}
const String getApplicationName() override { return ProjectInfo::projectName; }
const String getApplicationVersion() override { return ProjectInfo::versionString; }
bool moreThanOneInstanceAllowed() override { return true; }
//==============================================================================
void initialise (const String& commandLine) override
{
// This method is where you should put your application's initialisation code..
mainWindow.reset (new MainWindow (getApplicationName()));
}
void shutdown() override
{
// Add your application's shutdown code here..
mainWindow = nullptr; // (deletes our window)
}
//==============================================================================
void systemRequestedQuit() override
{
// This is called when the app is being asked to quit: you can ignore this
// request and let the app carry on running, or call quit() to allow the app to close.
quit();
}
void anotherInstanceStarted (const String& commandLine) override
{
// When another instance of the app is launched while this one is running,
// this method is invoked, and the commandLine parameter tells you what
// the other instance's command-line arguments were.
}
//==============================================================================
/*
This class implements the desktop window that contains an instance of
our MainComponent class.
*/
class MainWindow : public DocumentWindow
{
public:
MainWindow (String name) : DocumentWindow (name,
Desktop::getInstance().getDefaultLookAndFeel()
.findColour (ResizableWindow::backgroundColourId),
DocumentWindow::allButtons)
{
setUsingNativeTitleBar (true);
setContentOwned (new MainComponent(), true);
#if JUCE_IOS || JUCE_ANDROID
setFullScreen (true);
#else
setResizable (true, true);
centreWithSize (getWidth(), getHeight());
#endif
setVisible (true);
}
void closeButtonPressed() override
{
// This is called when the user tries to close this window. Here, we'll just
// ask the app to quit when this happens, but you can change this to do
// whatever you need.
JUCEApplication::getInstance()->systemRequestedQuit();
}
/* Note: Be careful if you override any DocumentWindow methods - the base
class uses a lot of them, so by overriding you might break its functionality.
It's best to do all your work in your content component instead, but if
you really have to override any DocumentWindow methods, make sure your
subclass also calls the superclass's method.
*/
private:
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainWindow)
};
private:
std::unique_ptr<MainWindow> mainWindow;
};
//==============================================================================
// This macro generates the main() routine that launches the app.
START_JUCE_APPLICATION (AudioOutApplication)
You need to remove the override from the function definition in the .cpp file. This specifier can only appear in a member function declaration (i.e., in the header file), unless you're defining the function inside the header file, in which case it can appear just before the function body.
How do I initialize DefenseThread so that it will start executing Defend()? I have seen a lot of examples on how to do it from a .cpp file without a header, but non with.
void CommandDefend::DefendStart()
Gets the following error:
'&' requires I-value
Header:
#pragma once
#include <thread>
class CommandDefend : public ICommand
{
public:
CommandDefend();
~CommandDefend();
private:
thread* DefenseThread;
/// <summary>
/// Starts the commands execution.
/// </summary>
void DefendStart();
/// <summary>
/// Does the actual defending.
/// </summary>
void Defend();
};
CPP:
#include "stdafx.h"
#include "CommandDefend.h"
void CommandDefend::DefendStart()
{//ERROR HERE!!!!!!
DefenseThread = new thread(&CommandDefend::Defend);
}
void CommandDefend::Defend()
{
}
If you replace
DefenseThread = new thread(&CommandDefend::Defend);
with
DefenseThread = new thread(&CommandDefend::Defend, this);
it should work, because it's the way how I initialize class members of type std::thread (while they are not pointers).
Getting error, when trying to run code. I am using Visual Forms. VS 2013
#include "MyForm.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThread]
int main(array<String^>^ args)
{
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Project1::MyForm form;
Application::Run(%form);
return 0;
}
MyForm.cpp(17): fatal error C1004: unexpected end-of-file found
MyForm.h:
#pragma once
namespace Project1 {
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 MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{
public:
MyForm(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
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->SuspendLayout();
//
// MyForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(284, 262);
this->Name = L"MyForm";
this->Text = L"MyForm";
this->Load += gcnew System::EventHandler(this, &MyForm::MyForm_Load);
this->ResumeLayout(false);
}
#pragma endregion
private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e) {
}
};
}
MyForm.cpp(17): fatal error C1004: unexpected end-of-file found
I just missed something in the code.
#include "MyForm.h"
using namespace System;
using namespace System ::Windows::Forms;
[STAThread]
void main(array<String^>^ arg) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Project1::MyForm form;
Application::Run(%form);
}
I'm a scholar for Computer Games Programming, currently studying C++. I'm trying to access a private Texture2D and Vector 2 type in a .h file from a .cpp file in order to give an object position and image.
This is the Player.cpp file
#include "Player.h"
#include <sstream>
Player::Player(int argc, char* argv[]) : Game(argc, argv), _cPlayerSpeed(0.1f), _cPlayerFrameTime(250)
{
//Player Inits
_playerDirection;
_playerFrame = 0;
_playerCurrentFrameTime = 0;
_playerSpeedMultiplier = 1.0f;
//Init of Important Game Aspects
Graphics::Initialise(argc, argv, this, 1024, 768, false, 25, 25, "Genocide: Remastered", 60);
Input::Initialise();
Graphics::StartGameLoop(); //Start of Game Loop, calls Update and Draw in game loop.
}
Player::~Player()
{
}
void Player::Input(int elapsedTime, Input::KeyboardState* state)
{
// Checks for directional keys pressed
if (state->IsKeyDown(Input::Keys::D))
{
_playerPosition->X += _cPlayerSpeed * elapsedTime;
}
}
/// <summary> All content should be loaded in this method. </summary>
void Player::LoadContent()
{
_playerPosition = new Vector2();
_playerTexture = new Texture2D();
_playerTexture->Load(" ", false);
_playerSourceRect = new Rect(0.0f, 0.0f, 0, 0);
}
/// <summary> Called every frame - update game logic here. </summary>
void Player::Update(int elapsedTime)
{
}
/// <summary> Called every frame - draw game here. </summary>
void Player::Draw(int elapsedTime)
{
}
This is the Player.h
#pragma once
#ifdef WIN32
#ifndef _DEBUG
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup")
#endif
#endif
#include "S2D/S2D.h"
using namespace S2D;
class Player : public Game
{
public:
Player(int argc, char* argv[]);
~Player();
/// <summary> All content should be loaded in this method. </summary>
void virtual LoadContent();
/// <summary> Called every frame - update game logic here. </summary>
void virtual Update(int elapsedTime);
/// <summary> Called every frame - draw game here. </summary>
void virtual Draw(int elapsedTime);
private:
Vector2* _playerPostion;
Rect* _playerSourceRect;
Texture2D* _pacmanTexture;
const float _cPlayerSpeed;
const int _cPlayerFrameTime;
int _playerDirection;
int _playerFrame;
int _playerCurrentFrameTime;
float _playerSpeedMultiplier;
void Input(int elapsedTime, Input::KeyboardState* state);
void CheckPaused(Input::KeyboardState* state, Input::Keys pauseKey);
void CheckViewportCollision();
void UpdatePlayer();
};
I've literally copied and pasted something I've been working on with my Lecturer and changed variable, type and instantiation declaration and his works. Curious as to why mine isn't. Help will be much appreciated.
Many thanks,
Ryan.
In the header, your Texture2D* is called _pacmanTexture, whereas in your implementation, you've called it _playerTexture. Similarly, you've misspelled _playerPosition in the header.
Usual way to give access to private resources of a class to another class is to add public accessor methods (getter, setter).
I have a problem, sorry for this newbie question (just a 2 week visual c++ programming experience). I am currently working with MDI in Visual C++2010, here is how the program works, once you execute the application, the MDIParent loads in maximize state, then the MDIParent has MenuStrip and one of its subMenu is named noviceToolStripMenuItem. If noviceToolStripMenuItem is clicked using the mouse button, it will open a child form called frmNovice, this works out fine, now the frmNovice contains a simple game which works out according to its intended function, once the game is over a new form named frmRetry will be shown but this time frmRetry is not a childform and the frmNovice will close. frmRetry has two buttons, Yes and No, if the user clicks the No the frmRetry will close and the MDIParent will then again holds the focus of the application, but if the user clicks the Yes button, the application should perform the click event/function of noviceToolStripMenuItem, to show up again the frmNovice, but this is the problem, i can't get this done. frmRetry (not a child form) to invoke or call the click event noviceToolStripMenuItem of the MDIParent. Is there any way to do this, or maybe other solution? thanks in advance.
This are the codes (some are deleted to minimize space):
**FILE: mdiMain.h**
#pragma once
#include "frmNovice.h"
namespace MemoryGame {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
public ref class Form1 : public System::Windows::Forms::Form {
public:
Form1(void)
{
InitializeComponent();
//TODO: Add the constructor code here
}
protected:
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::MenuStrip^ menuStrip1;
protected:
private: System::Windows::Forms::ToolStripMenuItem^ noviceToolStripMenuItem;
private:
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
void InitializeComponent(void)
{
this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip());
this->selectLevelToolStripMenuItem = (gcnew
System::Windows::Forms::ToolStripMenuItem());
this->noviceToolStripMenuItem = (gcnew
this->selectLevelToolStripMenuItem->Name = L"selectLevelToolStripMenuItem";
this->selectLevelToolStripMenuItem->Size = System::Drawing::Size(70, 20);
this->selectLevelToolStripMenuItem->Text = L"New &Game";
//
// noviceToolStripMenuItem
//
}
#pragma endregion
private: System::Void noviceToolStripMenuItem_Click(System::Object^ sen....) {
//OPENING NEW FORM AS MDI CHILD
frmNovice^ newMDIChild = gcnew frmNovice();
// Set the Parent Form of the Child window.
newMDIChild->MdiParent = this;
// Display the new form.
newMDIChild->Show();
}
};
}
FILE: mdiMain.cpp
#include "stdafx.h"
#include "mdiMain.h"
using namespace MemoryGame;
[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;
}
**FILE: frmNovice.h**
#pragma once
#include "frmRetry.h"
#include "algorithm"
namespace MemoryGame {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
public ref class frmNovice : public System::Windows::Forms::Form
{
public:
frmNovice(void)
{
InitializeComponent();
//TODO: Add the constructor code here
}
protected:
~frmNovice()
{
if (components)
{
delete components;
}
}
//codes for the UI of the game goes here.....
#pragma region Windows Form Designer generated code
//MY USER DEFINED FUNCTION START
void gamefunction() //this function is where calls the frmRetry to show
{
frmRetry^ form = gcnew frmRetry();
form->Show(); //This time not a CHILD FORM
this->Close();
}
void InitializeComponent(void)
{
//initialize UI components GOES HERE
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
//DIFFERENT PROCEDURE FUNCTIONS GOES HERE Also invokes/calls the game function that
//show the frmRetry (this is working properly)
};
}
FILE: frmNovice.cpp
#include "StdAfx.h"
#include "frmNovice.h"
//there are variables used for gameplay
int Choice1;
int Choice2;
int Mistakes;
int TimeRecord;
int AllItems;
and LASTLY
FILE: frmRetry.h
#pragma once
namespace MemoryGame {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
public ref class frmRetry : public System::Windows::Forms::Form
{
`enter code here`public:
frmRetry(void)
{
InitializeComponent();
}
protected:
~frmRetry()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Button^ btnYes;
private: System::Windows::Forms::Button^ btnNo;
protected:
private: System::Windows::Forms::PictureBox^ pictureBox1;
private:
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
void InitializeComponent(void)
{
CODES for UI inialization goes here
}
#pragma endregion
private: System::Void btnNo_Click(System::Object^ .....e) {
this->Close();
}
private: System::Void btnYes_Click(System::Object.....^ e) {
**THIS IS THE PART IM STuck WITH, i CANT GET THIS DONE**
**EVErything is working fine, except for this part where i have to
call again the frmNovice as an child form of the mdiParent**
THE following are my attempts but didnt work.
// frmRetry^ form = gcnew frmRetry();
// frmNovice^ frmNovice=gcnew frmNovice();
// noviceToolStripMenuItem->PerformClick();
//frmNovice->Show();
}
};
}
FILE: frmRetry.cpp
#include "StdAfx.h"
#include "frmRetry.h"
THANKS IN ADVANCE
You should pass in a reference to the main window when you create the Novice form, and pass this reference again to the Retry form. Then, have the main window implement a NoviceParent interface, which includes a public method for the Retry form to call. The noviceToolstripMenuItem_Click method on the main window will also delegate to this new public method.
Novice Parent Interface
public interface class INoviceParent
{
public:
void ShowNovice();
}
Main Window
#include "INoviceParent.h"
public ref class Form1 : public System::Windows::Forms::Form, INoviceParent {
public:
// ... existing public methods
void ShowNovice() {
//OPENING NEW FORM AS MDI CHILD
frmNovice^ newMDIChild = gcnew frmNovice(this);
// Set the Parent Form of the Child window.
newMDIChild->MdiParent = this;
// Display the new form.
newMDIChild->Show();
}
private:
void noviceTooltipMenuItem_Click( /* args */) {
ShowNovice();
}
// ...
};
Novice Form
#include "INoviceParent.h"
public ref class frmNovice : public System::Windows::Forms::Form
{
public:
frmNovice(INoviceParent ^ const parent)
{
this->parent = parent;
// ...
}
// ...
private:
void gamefunction() //this function is where calls the frmRetry to show
{
frmRetry^ form = gcnew frmRetry(parent);
form->Show(); //This time not a CHILD FORM
this->Close();
}
INoviceParent ^parent;
}
Retry Form
#include "INoviceParent.h"
public ref class frmRetry : public System::Windows::Forms::Form
{
public:
frmRetry(INoviceParent ^ const noviceParent)
{
this->noviceParent = noviceParent;
// ...
}
// ...
private: System::Void btnYes_Click(System::Object.....^ e) {
noviceParent->ShowNovice();
}
INoviceParent ^noviceParent;
};
The important thing here is that the sub-forms don't need to be strongly coupled to the main form or to each other. All they know is that the object passed in their constructor has a public method called ShowNovice(). The Retry form calls it when the user clicks the "Yes" button, and the main window does whatever it does when the user clicks its noviceTooltipMenuItem.