Creating a Windows Forms Control (C++) - c++

trying to run this basic form control example on msdn.
At step 1 of the portion "To add a custom property to a control" we place the ClickAnywhere code in the public section of the class.
First error: "error C2144: syntax error : 'bool' should be preceded by ';'"
Is this syntax correct in C++? (see below)
(removing the ClickAnywhere portion of code, it compiles fine...)
#pragma once
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
namespace clickcounter
{
/// <summary>
/// Summary for clickcounterControl
/// </summary>
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
public __gc class clickcounterControl : public System::Windows::Forms::UserControl
{
public:
//Problem code*****
property bool ClickAnywhere { //Is this syntax right in C++?
bool get() {
return (label1->Dock == DockStyle::Fill);
}
void set(bool val) {
if (val)
label1->Dock = DockStyle::Fill;
else
label1->Dock = DockStyle::None;
}
}
//End Problem code*****
clickcounterControl(void)
{
InitializeComponent();
}
protected:
void Dispose(Boolean disposing)
{
if (disposing && components)
{
components->Dispose();
}
__super::Dispose(disposing);
}
private: System::Windows::Forms::Label * label1;
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container* components;
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->label1 = new System::Windows::Forms::Label();
this->SuspendLayout();
//
// label1
//
this->label1->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;
this->label1->Location = System::Drawing::Point(32, 40);
this->label1->Name = S"label1";
this->label1->Size = System::Drawing::Size(30, 20);
this->label1->TabIndex = 0;
this->label1->Text = S"0";
this->label1->TextAlign = System::Drawing::ContentAlignment::MiddleCenter;
this->label1->Click += new System::EventHandler(this, label1_Click);
//
// clickcounterControl
//
this->Controls->Add(this->label1);
this->Name = S"clickcounterControl";
this->Size = System::Drawing::Size(100, 100);
this->ResumeLayout(false);
}
private: System::Void label1_Click(System::Object * sender, System::EventArgs * e)
{
int temp = System::Int32::Parse(label1->Text);
temp++;
label1->Text = temp.ToString();
}
};
}

Since you are using Visual Studio .Net 2003, you are using Managed C++, not C++/CLI. There is a significant difference in syntax. For a property, you must use the __property keyword, not the C++/CLI property keyword and its new style.
It should therefore be:
__property bool get_ClickAnywhere() {
return (label1->Dock == DockStyle::Fill);
}
__property void set_ClickAnywhere(bool value) {
if (value)
label1->Dock = DockStyle::Fill;
else
label1->Dock = DockStyle::None;
}
It looks like you are being tripped up by following a guide written for C++/CLI (Visual Studio 2005 and later) while still using Visual Studio 2003.

Related

How do i keep an integer after the code ran once?

I just started out on C# and I wanted to make a voice recognition program that counts your words and for now, warns you after a said number is passed. I have asked someone on discord and they said I should use a dictionary in order to do that but I don't know how to implement that into this so I made it with if statements, here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Recognition;
using System.Speech.Synthesis;
namespace VoiceRecognition
{
public partial class SpeechRecognition : Form
{
SpeechRecognitionEngine recEngine = new SpeechRecognitionEngine();
SpeechSynthesizer synthesizer = new SpeechSynthesizer();
public SpeechRecognition()
{
InitializeComponent();
}
private void On_Click(object sender, EventArgs e)
{
recEngine.RecognizeAsync(RecognizeMode.Multiple);
On.Enabled = true;
}
private void SpeechRecognition_Load(object sender, EventArgs e)
{
Choices commands = new Choices();
commands.Add(new string[] { "bad" });
GrammarBuilder gBuilder = new GrammarBuilder();
gBuilder.Append(commands);
Grammar grammar = new Grammar(gBuilder);
recEngine.LoadGrammarAsync(grammar);
recEngine.SetInputToDefaultAudioDevice();
recEngine.SpeechRecognized += recEngine_SpeechRecognized;
}
void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
switch (e.Result.Text)
{
case "bad":
int badwordcount = 0;
if (badwordcount == 0)
{
synthesizer.SpeakAsync("i will suggest you to stop.");
badwordcount +=1;
}
else if (badwordcount == 1)
{
synthesizer.SpeakAsync("You are getting quite annoying.");
badwordcount += 1;
}
if(badwordcount == 2)
{
synthesizer.SpeakAsync("Thats it, you are done.");
}
break;
}
}
private void Off_Click(object sender, EventArgs e)
{
recEngine.RecognizeAsyncStop();
Off.Enabled = false;
}
}
}
The problem lies in the integer from line 51 (badwordcount), no matter how much I repeat the word bad, it just does not respond with the "You are getting quite annoying." line. Any ideas on how do I save the integer so it knows what to say after it hears it a second time? (sorry for the long text, I don't know how to express my words very well).

Unity3D TestRunner hangs when using NSubstitute to mock a Monobehavior class

I have stripped my project down to the bare minimum to try to figure out this instance where Unity TestRunner hangs. I have two Monobehaviors classes, GameController and TrialController. I followed Jason Wiemann's excellent testing videos Everything you need to know about Testing in Unity3D and Testing Against Monobehaviors Using Mocks to create an interface class, ITrialController, so that I can mock it for testing GameController. The TestRunner hangs when I try to run TestWithGetNextSubstitute(). What am I doing wrong here?
============== GameCtrlTest.cs ===========================
using System.Collections;
using System.Collections.Generic;
using NSubstitute;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace Tests
{
public class GameCtrlTest
{
GameController gameCtrl;
[SetUp]
public void TestSetup()
{
GameObject gameObject = new GameObject("GameController");
gameCtrl = gameObject.AddComponent<GameController>();
gameCtrl.trialCtrl = Substitute.For<ITrialController>();
Assert.IsNotNull(gameCtrl.trialCtrl);
Debug.Log("Test Setup() done");
}
[UnityTest]
public IEnumerator TestWithGetNextSubstitute()
{
gameCtrl.trialCtrl.GetNextTrial().Returns( "test-1", "test-2", null);
yield return null;
}
}
}
================== TrialController.cs ================================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class TrialController : MonoBehaviour, ITrialController
{
int trialsLeft = 2;
public string GetNextTrial()
{
if (trialsLeft == 0)
return null;
else
{
string returnString = "trial--" + trialsLeft;
trialsLeft--;
return (returnString);
}
}
}
==================== ITrialController.cs =================
public interface ITrialController
{
string GetNextTrial();
}
==================== GameController.cs ==================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// give Test Runner access to internal variables and methods
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Tests")]
public class GameController : MonoBehaviour
{
public ITrialController trialCtrl { get; set; }
//=================== MonoBehavior interface =======================
void Awake()
{
Debug.Log("gameController Awake()");
}
// Start is called before the first frame update
void Start()
{
Debug.Log("gameController Start()");
if (trialCtrl != null)
Debug.Log("trialCtrl already set");
else
{
Debug.Log("calling FindObjectOfType(typeof(TrialController)");
trialCtrl = (ITrialController)FindObjectOfType(typeof(TrialController));
Debug.Assert(trialCtrl != null, "Problem finding TrialController");
}
}
// Update is called once per frame
static bool levelInitialized = false;
void Update()
{
if (!levelInitialized)
{
Debug.Log("gameController first Update()");
levelInitialized = true;
}
string trialName = trialCtrl.GetNextTrial();
while (trialName != null)
{
Debug.Log($"GameController got {trialName} from GetNextTrial");
trialName = trialCtrl.GetNextTrial();
}
}
}
The fix was to move the GetNextTrial().Returns() call from the [UnityTest] to the [Setup]. This initially seems very limiting, but there is probably a way to move the parameter list ("test-1", "test-2", null) into a variable so I can change it for different tests.
=============== GameCtrlTest.cs ===================================
using System.Collections;
using System.Collections.Generic;
using NSubstitute;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace Tests
{
public class GameCtrlTest
{
GameController gameCtrl;
[SetUp]
public void TestSetup()
{
GameObject gameObject = new GameObject("GameController");
gameCtrl = gameObject.AddComponent<GameController>();
gameCtrl.trialCtrl = Substitute.For<ITrialController>();
Assert.IsNotNull(gameCtrl.trialCtrl);
gameCtrl.trialCtrl.GetNextTrial().Returns("test-1", "test-2", null);
Debug.Log("Test Setup() done");
}
[UnityTest]
public IEnumerator TestWithGetNextSubstitute()
{
yield return null;
}
}
}

How to wait for data on a COM port

I am using .Net framework's SerialPort class (System.IO.Ports) and am trying to wait to receive data. I've looked around and the WaitCommEvent function seems to be what people suggest using, however it expects a HANDLE as the first parameter. I would like to know either how to get a handle from the SerialPort or a different way to wait for data compatible with the SerialPort class.
The SerialPort class has a DataReceived event:
Indicates that data has been received through a port represented by the SerialPort object.
The documentation provides the following C++/CLI example:
#using <System.dll>
using namespace System;
using namespace System::IO::Ports;
ref class PortDataReceived
{
public:
static void Main()
{
SerialPort^ mySerialPort = gcnew SerialPort("COM1");
mySerialPort->BaudRate = 9600;
mySerialPort->Parity = Parity::None;
mySerialPort->StopBits = StopBits::One;
mySerialPort->DataBits = 8;
mySerialPort->Handshake = Handshake::None;
mySerialPort->RtsEnable = true;
mySerialPort->DataReceived += gcnew SerialDataReceivedEventHandler(DataReceivedHandler);
mySerialPort->Open();
Console::WriteLine("Press any key to continue...");
Console::WriteLine();
Console::ReadKey();
mySerialPort->Close();
}
private:
static void DataReceivedHandler(
Object^ sender,
SerialDataReceivedEventArgs^ e)
{
SerialPort^ sp = (SerialPort^)sender;
String^ indata = sp->ReadExisting();
Console::WriteLine("Data Received:");
Console::Write(indata);
}
};
int main()
{
PortDataReceived::Main();
}

C++/cli override OnRender Event wpf

i try to bring a wpf "fire" (http://www.smartypantscoding.com/content/old-school-fire-algorithm-modern-day-wpf) Example to c++/cli. I translated it with a tool to c++/cli, but the overriden "OnRender" Event never get fired. So i see the Window like in the c# Project but without fire.
CompositionTarget_Rendering get called, and so normally InvalidateVisual() must fire the OnRender, but it doesn't. I hope u can help me =)
//the .h
#pragma once
using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Globalization;
using namespace System::Xml::Linq;
using namespace System::Text;
using namespace System::Windows::Documents;
using namespace System::Windows;
using namespace System::Windows::Media;
using namespace System::Windows::Media::Imaging;
using namespace System::Threading;
#include "FireGenerator.h"
/// <summary>
/// Adorner that disables all controls that fall under it
/// </summary>
public ref class FireAdorner : Adorner
{
private:
BitmapPalette ^_pallette;
literal int DPI = 96;
FireGenerator ^_fireGenerator;
/// <summary>
/// Constructor for the adorner
/// </summary>
/// <param name="adornerElement">The element to be adorned</param>
public:
FireAdorner(UIElement^ adornerElement);
private:
void CompositionTarget_Rendering(Object ^sender, EventArgs ^e);
/// <summary>
/// Called to draw on screen
/// </summary>
/// <param name="drawingContext">The drawind context in which we can draw</param>
protected:
virtual void OnRender(System::Windows::Media::DrawingContext ^drawingContext) override;
private:
BitmapPalette ^SetupFirePalette();
private:
void InitializeInstanceFields();
};
and the .cpp
#include "StdAfx.h"
#include "FireAdorner.h"
using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Globalization;
using namespace System::Xml::Linq;
using namespace System::Text;
using namespace System::Windows::Documents;
using namespace System::Windows;
using namespace System::Windows::Media;
using namespace System::Windows::Media::Imaging;
using namespace System::Threading;
FireAdorner::FireAdorner(UIElement ^adornerElement) : Adorner(adornerElement)
{
InitializeInstanceFields();
CompositionTarget::Rendering += gcnew EventHandler(this, &FireAdorner::CompositionTarget_Rendering);
}
void FireAdorner::CompositionTarget_Rendering(Object ^sender, EventArgs ^e)
{
InvalidateVisual();
}
void FireAdorner::OnRender(System::Windows::Media::DrawingContext ^drawingContext)
{
System::Windows::MessageBox::Show("render");
// only set the pallette once (dont do in constructor as causes odd errors if exception occurs)
if (_pallette == nullptr)
{
_pallette = SetupFirePalette();
}
_fireGenerator->UpdateFire();
BitmapSource ^bs = BitmapSource::Create(_fireGenerator->Width, _fireGenerator->Height, DPI, DPI, PixelFormats::Indexed8, _pallette, _fireGenerator->FireData, _fireGenerator->Width);
drawingContext->DrawImage(bs, Rect(0, 0, this->DesiredSize.Width, this->DesiredSize.Height));
}
BitmapPalette ^FireAdorner::SetupFirePalette()
{
System::Collections::Generic::List<Color> ^myList = gcnew System::Collections::Generic::List<Color>();
// seutp the basic array we will modify
for (int i = 0; i <= 255; i++)
{
myList->Add(Color());
}
for (int i = 0; i < 64; i++)
{
Color c1 = Color();
c1.R = safe_cast<Byte>(i * 4);
c1.G = safe_cast<Byte>(0);
c1.B = safe_cast<Byte>(0);
c1.A = 255;
myList[i] = c1;
Color c2 = Color();
c2.R = safe_cast<Byte>(255);
c2.G = safe_cast<Byte>(i * 4);
c2.B = safe_cast<Byte>(0);
c2.A = 255;
myList[i + 64] = c2;
Color c3 = Color();
c3.R = safe_cast<Byte>(255);
c3.G = safe_cast<Byte>(255);
c3.B = safe_cast<Byte>(i * 4);
c3.A = 255;
myList[i + 128] = c3;
Color c4 = Color();
c4.R = safe_cast<Byte>(255);
c4.G = safe_cast<Byte>(255);
c4.B = safe_cast<Byte>(255);
c4.A = 255;
myList[i + 192] = c4;
}
BitmapPalette ^bp = gcnew BitmapPalette(myList);
return bp;
}
void FireAdorner::InitializeInstanceFields()
{
_fireGenerator = gcnew FireGenerator(600, 50);
}
Initcode:
FireAdorner^ myfire = gcnew FireAdorner(MyWindow);
MyWindow->ShowDialog();
//MyWindow is a Window^ created from this Code:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Fire" Width="800" Height="200" Closing="Window_Closing">
<Grid>
<AdornerDecorator>
<DockPanel Name="dockPanel1"/>
</AdornerDecorator>
<!-- This rectangle is a hack to hide the bottom rows of the fire which look blocky
the proper solution would be to fix the rendering to leave off the bottom XX lines -->
<Rectangle Fill="Black" VerticalAlignment="Bottom"
Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, Path=ActualWidth}"
Height="8" />
</Grid>
</Window>
This solved the Problem:
old not working Initcode:
FireAdorner^ myfire = gcnew FireAdorner(MyWindow);
MyWindow->ShowDialog();
new Initcode:
DockPanel^ firebox = (DockPanel^)MyWindow->FindName("dockPanel1");
AdornerLayer^ adornerLayer = AdornerLayer::GetAdornerLayer(firebox);
adornerLayer->Add(gcnew FireAdorner(firebox));
MyWindow->ShowDialog();

XamComboEditor SelectedItemChangedEvent firing non-stop in XamDataGrid

I have bound XamComboEditor's in two columns of XamDataGrid. When I select an item from XamComboEditor1, I would like to bind specific items to XamComboEditor2. I have attached SelectedItemChanged Event to XamComboEditor1. The event fires non-stop on selecting an item.
XAML-
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:igDP="http://infragistics.com/DataPresenter"
xmlns:igRibbon="http://infragistics.com/Ribbon"
xmlns:igOB="http://infragistics.com/OutlookBar"
xmlns:igDock="http://infragistics.com/DockManager"
xmlns:igTiles="http://infragistics.com/Tiles"
xmlns:igEditors="http://infragistics.com/Editors"
Title="Window1" Height="300" Width="720">
<Window.Resources>
</Window.Resources>
<Grid>
<DockPanel LastChildFill="True" Margin="0,26,0,-26">
<igDP:XamDataGrid x:Name="XamDataGrid1">
</igDP:XamDataGrid>
</DockPanel>
</Grid>
</Window>
Code Behind -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Infragistics.Windows.DataPresenter;
using Infragistics.Windows.Editors;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
EventManager.RegisterClassHandler(typeof(ValueEditor),
ValueEditor.ValueChangedEvent,
new RoutedPropertyChangedEventHandler<object>(OnValueChanged));
ComboBoxItemsProvider provider = new ComboBoxItemsProvider();
for (int i = 0; i < 6; i++)
provider.Items.Add(new ComboBoxDataItem(i, "Item " + i.ToString()));
FieldLayout fieldLayout = new FieldLayout();
UnboundField fld1 = new UnboundField();
fld1.Name = "Visibility Setting1";
Style style1 = new Style(typeof(XamComboEditor));
style1.Setters.Add(new Setter(XamComboEditor.ItemsProviderProperty, provider));
style1.Setters.Add(new EventSetter(XamComboEditor.SelectedItemChangedEvent, new RoutedPropertyChangedEventHandler<object>(XamComboEditor1_SelectedItemChanged)));
fld1.Settings.EditorStyle = style1;
fld1.Settings.EditorType = typeof(XamComboEditor);
fieldLayout.Fields.Add(fld1);
UnboundField fld2 = new UnboundField();
fld2.Name = "Visibility Setting2";
Style style2 = new Style(typeof(XamComboEditor));
fld2.Settings.EditorStyle = style2;
fld2.Settings.EditorType = typeof(XamComboEditor);
fieldLayout.Fields.Add(fld2);
this.XamDataGrid1.FieldLayouts.Add(fieldLayout);
this.XamDataGrid1.BindToSampleData = true;
}
void OnValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (sender is XamComboEditor || sender is XamCheckEditor || sender is XamDateTimeEditor)
{
(sender as ValueEditor).EndEditMode(true, true);
if (sender is XamComboEditor)
{
XamComboEditor comboEditor = (XamComboEditor)sender;
}
}
}
private void XamComboEditor1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
// Create combo box items provider for freight modes
ComboBoxItemsProvider provider = new ComboBoxItemsProvider();
for (int i = 0; i < 10; ++i)
{
provider.Items.Add(new ComboBoxDataItem(i.ToString(), i.ToString()));
}
//// Get unbound field associated with index
Record record = this.XamDataGrid1.ActiveRecord;
// Get the combo editor with record
UnboundField uFld = (UnboundField)record.FieldLayout.Fields[1];
// Set style for uFld
Style style = new Style(typeof(XamComboEditor));
style.Setters.Add(new Setter(XamComboEditor.ItemsProviderProperty, provider));
style.Setters.Add(new Setter(XamComboEditor.DropDownResizeModeProperty, Infragistics.Windows.Controls.PopupResizeMode.None));
style.Setters.Add(new Setter(XamComboEditor.IsAlwaysInEditModeProperty, false));
style.Setters.Add(new EventSetter(XamComboEditor.SelectedItemChangedEvent, new RoutedPropertyChangedEventHandler<object>(XamComboEditor2_SelectedItemChanged)));
style.Setters.Add(new Setter(XamComboEditor.IsEditableProperty, false));
uFld.Settings.EditorStyle = style;
uFld.Settings.EditorType = typeof(XamComboEditor);
uFld.Settings.InvalidValueBehavior = InvalidValueBehavior.RetainValue;
uFld.Settings.AllowCellVirtualization = false;
e.Handled = true;
}
private void XamComboEditor2_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
}
}
}
Shouldn't be referring back to the style in the unbound field.
Found solution at -
http://blogsprajeesh.blogspot.com/2010/03/infragistics-working-with-2.html