2008年10月8日水曜日

C#2005/2008 マネージ 線形リスト クラス

C#2005/2008 マネージ 線形リスト クラス

マネージで線形リストが扱えるクラス(List.cs)を作りました。マネージでは new の代わりに gcnew を使用するため、関数のスコープが外れたときでも gcnew で確保した内容が消えないようにしなければなりません。
以下は、線形リストで追加と削除ができるクラスです。先入れ先出のみの対応で、リストの真ん中に対して挿入・削除は対応しておりません。

**** Form1.cs ****

private void button3_Click(object sender, EventArgs e)
{
List list = new List();

ListType input = new ListType(256);
input.buff[0] = 1;
input.buff[1] = 2;
list.addlist(input); // リストへ追加 1
input.Clear();
input.buff[0] = 3;
input.buff[1] = 4;
list.addlist(input); // リストへ追加 2

ListType getd = new ListType(256);
getd = list.deletelist(); // リスト取得後削除 1
getd = list.deletelist(); // リスト取得後削除 2
getd = list.deletelist(); // リスト取得後削除 (nullを返す)
}

**** List.cs ****

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestTest
{
/// <summary>
/// リストタイプ クラス
/// </summary>
class ListType
{
///------------------------------------------------
/// テーブル宣言
///------------------------------------------------
public Int32 no; // リスト番号
public uint[] buff; // 格納データ
public Int32 len; // 文字数
public ListType next; // 次の要素へのポインタ
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="length"></param>
public ListType( Int32 length )
{
buff = new uint[length];
len = length;
next = null;
Clear(); // バッファクリア
}
public void Clear()
{
for (Int32 ii = 0; ii < len; ii++)
{
buff[ii] = 0;
}
}
}
///--------------------------------------------------------
/// <summary>
/// リスト クラス
/// </summary>
class List
{
///------------------------------------------------
/// テーブル宣言
///------------------------------------------------
public ListType head;
public ListType p;
public ListType q;
public ListType newcell;
public ListType output;
public Int32 No;
/// <summary>
/// コンストラクタ
/// </summary>
public List()
{
head = new ListType(1); // リストヘッダー宣言
No = 0;
}
/// <summary>
/// リスト追加
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public bool addlist( ListType input )
{
p = head.next; // 先頭要素の次のアドレス
q = head; // 先頭のアドレス
while( p != null )
{
q = p; // 追加位置の直前の要素nextを後で設定するため
p = p.next; // 次の要素へ進む
}

newcell = new ListType(input.len);
if( newcell == null )
{
return false; // メモリ不足
}

input.no = ++No;
for (Int32 ii = 0; ii < (input.len); ii++)
{
newcell.buff[ii] = input.buff[ii]; // 新しい要素を設定
}
newcell.len = input.len; // 文字数設定
newcell.next = p; // 新しい要素の次の要素へのアドレス設定
q.next = newcell; // 新しい要素の直前の要素のnextに新しい要素アドレス設定
return true;
}
/// <summary>
/// リスト削除
/// </summary>
/// <returns></returns>
public ListType deletelist()
{
p = head.next; // 先頭要素の次の要素アドレス
q = head; // 先頭要素アドレス

if( p == null )
{
return null;
}
else
{
output = new ListType(p.len); // 取出領域確保
output.no = --No;
for(Int32 ii=0; ii<(p.len); ii++)
{
output.buff[ii] = p.buff[ii];
}
output.len = p.len;
q.next = p.next; // 削除する要素の直前の要素のnextポインタを再設定
p = null;
}
return output;
}
}
}

2008年6月25日水曜日

VC#2008 型 DLL対応について

VC#2008 型 DLL対応について

C#の変数のDLL対応について記述します。

[Windows] : [C] : [C#] : [.NET]
-----------------------------------------
BOOL : long : bool : System.Boolean
BYTE : unsigned char : byte : System.Byte
--- : --- : sbyte : System.SByte
CHAR : char : char : System.Char
--- : --- : decimal : System.Decimal
DOUBLE : double : double : System.Double
FLOAT : float : float : System.Single
SHORT : short : short : System.Int16
INT : int : int : System.Int32
LONG : long : long : System.Int32
UINT : unsigned int : uint : System.UInt32
ULONG : unsigned long : uint : System.UInt32
WORD : unsigned short : ushort : System.UInt16
LPSTR : char* : --- : System.Text.StringBuilder
LPCSTR : const char* : string : System.String

2008年6月18日水曜日

VC#2008 型 .NETの関係について

VC#2008 型 .NETの関係について

C#と.NETの変数の型について記述します。
[C#] [.NET]
bool → System.Boolean
byte → System.Byte
sbyte → System.SByte
char → System.Char
decimal → System.Decimal
double → System.Double
float → System.Single
short → System.Int16
int → System.Int32
long → System.Int64
ushort → System.UInt16
uint → System.UInt32
ulong → System.UInt64
string → System.String

2008年6月11日水曜日

>Form1 にツールボックスの以下のコントロールを配置のやり方がわかりません




図(1)ツールボックスのButtonやListViewを左クリックで選択状態にしておき、Form1[デザイン]に左クリックで配置します。

図(2)ツールボックスのserialPortを左クリックで選択状態にしておき、
Form1[デザイン]に左クリックで配置します。すると、フォーム上に配置されずに外の下側に配置されます。

図(3)Button1をダブルクリックすると、画面がソースコードへ切替わって、イベントハンドラが自動的に作成されます。


また質問等あれば遠慮なくどうぞ!

2008年5月27日火曜日

SQL Server データベースの作り方

SQL Server データベースの作り方

■以下のソフトがインストールされていることを確認する。なければインストールする。
スタート -> すべてのプログラム -> Microsoft SQL Server 2005 を確認する。
1) SQL構成マネージャー(SQL Server Configuration Manager)
2) Microsoft SQL Server Management Studio Express

■SQL Serverの認証を許可する
1)SQL構成マネージャー(SQL Server Configuration Manager)を起動する。
2)SQL Server 2005 ネットワークの構成 -> SQLEXPRESS のプロトコル -> 名前付きパイプ を「有効」にする

■データベースを作成する
1)Microsoft SQL Server Management Studio Express を起動する。
2)[新しいクエリ]で 以下を貼り付けて実行する。
------ 貼り付けるテキスト ------
CREATE DATABASE [TestDB] ON (NAME = 'TestDB_Data', FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\TestDB_Data.MDF') LOG ON (NAME = 'TestDB_Log', FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\TestDB_Log.LDF')
GO

use [TestDB]
GO

CREATE TABLE [dbo].[顧客] (
[ID] [int] PRIMARY KEY ,
[姓] [ntext] ,
[名] [ntext] ,
[姓かな] [ntext] ,
[名かな] [ntext] ,
[性別] [int] ,
[自宅パソコンメール] [bit] ,
[携帯メール] [bit] ,
[職場パソコンメール] [bit] ,
[その他メール] [bit] ,
[その他メールの説明] [ntext] ,
[メールアドレス] [ntext] ,
[誕生日] [datetime] ,
[電話番号] [ntext]
)
GO

CREATE TABLE [dbo].[性別] (
[ID] [int] PRIMARY KEY ,
[名称] [ntext]
)
GO
------ 貼り付けるテキスト ------

2008年5月17日土曜日

VC++2005/2008 get() set() を property で実現する

VC++2005/2008 get() set() を property で実現する

クラスのメンバ変数をアクセスするのに get() set() メソッドを用意するのは一般的ですが、property を利用すればすっきり記述できます。

■property を使ったクラス
public ref class pro
{
private: Byte tbl_; // プライベート宣言
public: property Byte tbl // get() set() の tblパブリック宣言
{
void set(Byte val)
{
tbl_ = val;
}
Byte get()
{
return tbl_;
}
}
};
■呼出側
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
pro^ pp = gcnew pro();
pp->tbl = 10;
}

VC++2005/2008 配列を array でマネージ化

VC++2005/2008 配列を array でマネージ化

配列をマネージ化したとき以下のようになります。

■ネイティブ
unsigned char aaa[3];
aaa[0] = 1;
aaa[1] = 2;
aaa[2] = 3;
unsigned char bbb[3];
memcpy( bbb , aaa , sizeof(bbb) );

■マネージ
array<Byte>^ aaa = gcnew array<Byte>(3);
aaa[0] = 1;
aaa[1] = 2;
aaa[2] = 3;
array<Byte>^ bbb = gcnew array<Byte>(3);
aaa->CopyTo(bbb, 0);

■ちなみに文字数を調べるには sizeof() 以下のようにします。

Int32 len = aaa->Length;

2008年5月15日木曜日

VC++2005/2008 マネージ 線形リスト クラス

VC++2005/2008 マネージ 線形リスト クラス

マネージで線形リストが扱えるクラス(List.h)を作りました。マネージでは new の代わりに gcnew を使用するため、関数のスコープが外れたときでも gcnew で確保した内容が消えないようにしなければなりません。
以下は、線形リストで追加と削除ができるクラスです。先入れ先出のみの対応で、リストの真ん中に対して挿入・削除は対応しておりません。

**** List.h ****
#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;

///------------------------------------------------
/// ■リストタイプクラスの先頭
///------------------------------------------------
ref class CListType
{
public: Int32 no; // リスト番号
public: array<unsigned char>^ buff; // 格納データ
public: Int32 len; // 文字数
public: CListType^ next; // 次の要素へのポインタ
///------------------------------------------------
/// コンストラクタ
///------------------------------------------------
public: CListType(Int32 length)
{
buff = gcnew array<unsigned char>(length);
len = length;
next = nullptr;
}
///------------------------------------------------
}; // ■クラスの最後
///------------------------------------------------


///------------------------------------------------
/// ■リストクラスの先頭
///------------------------------------------------
ref class CList
{
///------------------------------------------------
/// テーブル宣言
///------------------------------------------------
public: CListType^ head; // リストの先頭要素(ダミー)
public: CListType^ p;
public: CListType^ q;
public: CListType^ newcell;
public: CListType^ output;
public: Int32 No;
///------------------------------------------------
/// コンストラクタ
///------------------------------------------------
public: CList()
{
head = gcnew CListType(1); // リストヘッダー宣言
No = 0;
}
///------------------------------------------------
/// 追加
///------------------------------------------------
public: bool addlist(CListType^ input)
{
p = head->next; // 先頭要素の次の要素のアドレス
q = head; // 先頭要素のアドレス
while( p != nullptr )
{
q = p; // 追加位置の直前の要素のnextを後で設定するために、追加位置の直前の要素のアドレスを記憶しておく
p = p->next; // 次の要素へ進む
}

newcell = gcnew CListType(input->len); // 新しく追加する要素のためのメモリ領域を確保する
if( newcell == nullptr ){
return false; // メモリ不足
}

input->no = ++No;
for(Int32 ii=0; ii<(input->len); ii++){
newcell->buff[ii] = input->buff[ii]; // 新しい要素のデータを設定
}
newcell->len = input->len; // 文字数設定
newcell->next = p; // 新しい要素の次の要素へのアドレスを設定
q->next = newcell; // 新しい要素の直前の要素のnextに、新しい要素のアドレスを設定
return true;
}
///------------------------------------------------
/// 削除
///------------------------------------------------
public: CListType^ deletelist(void)
{
p = head->next; // 先頭要素の次の要素のアドレス
q = head; // 先頭要素のアドレス

if( p == nullptr ){ // リストの末尾
return nullptr;
}
else{
output = gcnew CListType(p->len); // 取出領域確保
output->no = --No;
for(Int32 ii=0; ii<(p->len); ii++){
output->buff[ii] = p->buff[ii]; // 新しい要素のデータを設定
}
output->len = p->len;

q->next = p->next; // 削除する要素の直前の要素のnextポインタを再設定
delete p;
}
return output;
}

///------------------------------------------------
}; // ■クラスの最後
///------------------------------------------------

2008年5月7日水曜日

System::String型で mid() に相当する Substring() の使い方

System::String型で mid() に相当する Substring() の使い方

CString型の mid() に相当するのが Substring() です。取得失敗に備えて try - catch で覆ったほうがよいでしょう。

System::String^ textString = "abcde";
System::String^ moji;
System::String^ err = "";

try
{
moji = textString->Substring(1,1);
}
catch(Exception^ e)
{
err = System::String::Format("{0}",e);
}

2008年4月24日木曜日

VC++2005/2008 コンボボックスの使用方法

VC++2005/2008 コンボボックスの使用方法
コンボボックスはテキストボックスとリストボックスを組合わせた便利なコンポーネントです。おもな使用方法を示します。

array<System::String^>^ arr = gcnew array<System::String^>{"bbb","ccc"}; // 配列宣言

comboBox1->Items->Clear(); // コンボボックスのアイテムクリア
comboBox1->Items->Add( "aaa" ); // コンボボックスにアイテム1つ追加
comboBox1->Items->AddRange( arr ); // コンボボックスにアイテムまとめて追加
comboBox1->Text = String::Format("{0} : {1}",comboBox1->Items->Count , comboBox1->Items[0] ); // コンボボックスのテキスト表示

2008年4月23日水曜日

VC++2005/2008 .NET SerialPort を使用する方法

VC++2005/2008 .NET SerialPort を使用する方法

.NET の SerialPort を使用してシリアル送受信する方法を示します。
SerialPort はそのまま使うよりクラス(CUartクラス)にラップするほうがすっきりします。
シリアル受信はスレッドで行い、受信データをデリゲート渡しにしてテキストボックスに表示します。

■■ Uart.h (CUartクラス) ■■■■■■■■■■■■■■■■■■■■■■■
#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;
using namespace System::IO::Ports; // シリアルポート

#define BUF_SIZE 10

ref class CUart
{
///------------------------------------------------
/// テーブル宣言
///------------------------------------------------
public: SerialPort^ port;
public: System::String^ nowPort;

///------------------------------------------------
/// コンストラクタ
///------------------------------------------------
public:CUart()
{
nowPort = "----"; // 現在ポート名クリア
port = gcnew SerialPort(); // シリアルポートインスタンス化
}
///------------------------------------------------
/// オープン可能ポート調査
///------------------------------------------------
public: System::String^ portInvestigation()
{
String^ na = nowPort;
if( na != "----" ){ // 現在ポートオープン中のとき
port->Close(); // ポートクローズ
}
array<String^>^ ports = SerialPort::GetPortNames(); // 全ポート名取得
ports->Sort( ports ); // 並び替え
char ct = ports->Length::get();

array<String^>^ names = gcnew array<String^>(ct); // 利用可能なポート名取得
char cnt = 0;
for(char ii=0; ii<ct; ii++)
{
if( portOpenTest( ports[ii] ) == true ){ // オープンに成功したとき
names[cnt++] = ports[ii]; // ポート名取得
}
}

char flg = 0;
if( nowPort == "----" ){
flg = 1;
}
for(char ii=0; ii<cnt; ii++)
{
if( names[ii] == nowPort ){ // 現在のポートと同じ時
flg = 1;
}
else{
if( flg == 1 ){
nowPort = names[ii];
break;
}
}
}

if( na == nowPort ){
nowPort = "----";
}
return nowPort;
}
///------------------------------------------------
/// ポートオープンテスト
///------------------------------------------------
private: bool portOpenTest( System::String^ name )
{
port->Close();
bool result = portOpen( name );
port->Close();
return result;
}
///------------------------------------------------
/// ポートオープン
/// SerialPort port = new SerialPort(COM4, 9600, Parity.None, 8, StopBits.One);
///------------------------------------------------
public: bool portOpen( System::String^ name )
{
System::String^ err = "";
port->PortName = name; // ポート名設定
port->BaudRate = 9600;
port->Parity = Parity::None;
port->StopBits = StopBits::One;
try
{
port->Open(); // ポートオープン
}
catch(Exception^ e)
{
err = System::String::Format("{0}",e);
}
if( err == "" ){
return true;
}
else{
return false;
}
}
///------------------------------------------------
/// 送信
///------------------------------------------------
public: void write( array<unsigned char>^ buffer, int offset, int count )
{
port->Write( buffer , offset , count );
}
///------------------------------------------------
/// 受信
///------------------------------------------------
public: void read( array<unsigned char>^ buffer, int offset, int count )
{
System::String^ err = "";
try
{
port->Read( buffer , offset , count );
}
catch(Exception^ e)
{
err = System::String::Format("{0}",e);
}
}
///------------------------------------------------
/// オープンしているかどうか
///------------------------------------------------
public: bool isOpen()
{
return port->IsOpen::get();
}
///------------------------------------------------
};
■■ Form1.h ■■■■■■■■■■■■■■■■■■■■■■■
※必要な部分だけを記載しています。
///------------------------------------------
/// ■インクリュード宣言
///------------------------------------------
#include "Uart.h"
///------------------------------------------
/// ■変数宣言
///------------------------------------------
private: CUart^ uart;
private: array<unsigned char>^ buff;
private: bool RxLoopFlg;
///------------------------------------------
/// ■ボタン1
/// シリアルポート設定(変更)
///------------------------------------------
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
String^ com = uart->portInvestigation();
if( com == "----" ){
textBox1->Text = com;
RxLoopFlg = false;
}
else{
if( uart->portOpen(com) == true ){
textBox1->Text = com;
RxLoopFlg = true;
}
else{
textBox1->Text = "失敗";
RxLoopFlg = false;
}
}
}
///------------------------------------------
/// ■ボタン2
/// シリアル送信(適当な値を送信)
///------------------------------------------
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
array<unsigned char>^ buff = gcnew array<unsigned char>(BUF_SIZE);
for(char ii=0 ; ii<BUF_SIZE; ii++){
buff[ii] = 0x30 + ii;
}
uart->write( buff , 0 , BUF_SIZE);
}
///------------------------------------------
/// ■フォームロード
///------------------------------------------
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) {
RxLoopFlg = false;
buff = gcnew array<unsigned char>(BUF_SIZE); // シリアル受信バッファ領域宣言
buff->Clear(buff,0,BUF_SIZE); // シリアル受信バッファクリア
uart = gcnew CUart(); // シリアルポートインスタンス
button1_Click(sender,e); // シリアルポート設定(変更)
backgroundWorker1->RunWorkerAsync(); // スレッド開始(シリアル受信)
}
///------------------------------------------
/// ■デリゲート
/// ■テキストボックスセット
///------------------------------------------
delegate void SetTextCallback(array<unsigned char>^ buff);
private: void SetText_A(array<unsigned char>^ buff){
if( this->textBox2->InvokeRequired ){
SetTextCallback^ d = gcnew SetTextCallback(this, &at3200::Form1::SetText_A);
this->BeginInvoke( d, buff );
}
else{
unsigned char bf[BUF_SIZE];
for(char ii=0; ii<BUF_SIZE; ii++){
bf[ii] = buff[ii];
}
buff->Clear(buff,0,BUF_SIZE); // シリアル受信バッファクリア
// this->textBox2->Text += System::Runtime::InteropServices::Marshal::PtrToStringAnsi((IntPtr)bf);
this->textBox2->AppendText(System::Runtime::InteropServices::Marshal::PtrToStringAnsi((IntPtr)bf));
}
}
///------------------------------------------
/// ■スレッド1
///------------------------------------------
private: System::Void backgroundWorker1_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) {
while(1){
if( RxLoopFlg == true ){
if( uart->isOpen() == true ){
uart->read( buff , 0 , BUF_SIZE ); // シリアル受信
SetText_A( buff );
}
else{
}
}
else{
}
}
}
■■ Form1.h の終わり ■■■■■■■■■■■■■■■■■■

2008年4月15日火曜日

VC++2005/2008 シリアルポートを使用する

VC++2005/2008 シリアルポートを使用する

ボタン1を押すと、listBox1に全ポート名、listBox2に使用可能なポート名を表示します。

[ツールボックス]->[コンポーネント]->[SerialPort]を貼り付けて、以下のソースを使用します。


using namespace System::IO::Ports; // シリアルポート


public: SerialPort port; // シリアルポート宣言


private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {

listBox1->Items->Clear(); // リストボックス1初期化
array<System::String^>^ names = SerialPort::GetPortNames(); // ポート名取得
listBox1->Items->AddRange( names ); // リストボックス1へ出力する
// listBox1->Items->AddRange( SerialPort::GetPortNames() );

listBox2->Items->Clear(); // リストボックス2初期化
for(char ii=0; iiItems->Count; ii++)
{
System::String^ name;
try
{
name = listBox1->Items[ii]->ToString();
port.PortName = name;
port.Open();
}
catch(Exception^ e)
{
name = System::String::Format("{0}",e);
}
finally
{
port.Close();
if( name != "" )
{
listBox2->Items->Add(name);
}
}
}
}
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
できるだけ詳しく記述しました。よろしくお願いします。
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
(1)プロジェクトを simpleUart という名前で新規作成します。
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

■[ファイル]→[新規作成]→[プロジェクト]→ simpleUart

■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
(2)Form1 にツールボックスの以下のコントロールを配置し、イベントハンドラを作成します。
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

①Button1 (コモンコントロール)
②ListBox1 (コモンコントロール)
③ListBox2 (コモンコントロール)
④serialPort1 (コンポーネント)
⑤Button1のイベントハンドラを作成します。(Button1ダブルクリックで "button1_Click"を作成します)

■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
(3)Form.h の全ソースコードを以下に示します。
↓追加 ~↑追加で囲まれた部分がデフォルトから追加したところを示します。
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
// ソースコードの始まり
// ■注意■ ">"と"<"は全角なので半角に置換してください。
// (半角ではHTML表示で問題があるため)

#pragma once


namespace simpleUart {

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::Ports; // シリアルポート
// ■■■■■■■■■■■■■■■■■↑追加

/// <summary>
/// Form1 の概要
///
/// 警告: このクラスの名前を変更する場合、このクラスが依存するすべての .resx ファイルに関連付けられた
/// マネージ リソース コンパイラ ツールに対して 'Resource File Name' プロパティを
/// 変更する必要があります。この変更を行わないと、
/// デザイナと、このフォームに関連付けられたローカライズ済みリソースとが、
/// 正しく相互に利用できなくなります。
/// </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::IO::Ports::SerialPort^ serialPort1;
protected:
private: System::Windows::Forms::ListBox^ listBox1;
private: System::Windows::Forms::ListBox^ listBox2;
private: System::Windows::Forms::Button^ button1;
private: System::ComponentModel::IContainer^ components;

private:
/// <summary>
/// 必要なデザイナ変数です。
/// </summary>
// ■■■■■■■■■■■■■■■■■↓追加
public: SerialPort port; // シリアルポート宣言
// ■■■■■■■■■■■■■■■■■↑追加


#pragma region Windows Form Designer generated code
/// <summary>
/// デザイナ サポートに必要なメソッドです。このメソッドの内容を
/// コード エディタで変更しないでください。
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
this->serialPort1 = (gcnew System::IO::Ports::SerialPort(this->components));
this->listBox1 = (gcnew System::Windows::Forms::ListBox());
this->listBox2 = (gcnew System::Windows::Forms::ListBox());
this->button1 = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// listBox1
//
this->listBox1->FormattingEnabled = true;
this->listBox1->ItemHeight = 12;
this->listBox1->Location = System::Drawing::Point(13, 43);
this->listBox1->Name = L"listBox1";
this->listBox1->Size = System::Drawing::Size(106, 76);
this->listBox1->TabIndex = 0;
//
// listBox2
//
this->listBox2->FormattingEnabled = true;
this->listBox2->ItemHeight = 12;
this->listBox2->Location = System::Drawing::Point(144, 43);
this->listBox2->Name = L"listBox2";
this->listBox2->Size = System::Drawing::Size(106, 76);
this->listBox2->TabIndex = 1;
//
// button1
//
this->button1->Location = System::Drawing::Point(13, 10);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(85, 22);
this->button1->TabIndex = 2;
this->button1->Text = L"button1";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 12);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(292, 266);
this->Controls->Add(this->button1);
this->Controls->Add(this->listBox2);
this->Controls->Add(this->listBox1);
this->Name = L"Form1";
this->Text = L"Form1";
this->ResumeLayout(false);

}
#pragma endregion
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
// ■■■■■■■■■■■■■■■■■↓追加
listBox1->Items->Clear(); // リストボックス1初期化
array<System::String^>^ names = SerialPort::GetPortNames(); // ポート名取得
listBox1->Items->AddRange( names ); // リストボックス1へ出力する
listBox2->Items->Clear(); // リストボックス2初期化
for(char ii=0; ii<listBox1->Items->Count; ii++)
{
System::String^ name;
try
{
name = listBox1->Items[ii]->ToString();
port.PortName = name;
port.Open();
}
catch(Exception^ e)
{
name = System::String::Format("{0}",e);
}
finally
{
port.Close();
if( name != "" )
{
listBox2->Items->Add(name);
}
}
}
}
// ■■■■■■■■■■■■■■■■■↑追加
};
}

// ソースコードの終わり

■■■■■■■■■■■■■■■■■■■■■■■■
質問の回答は最新のブログで記載させていただきました。
■■■■■■■■■■■■■■■■■■■■■■■■


■■■■■■■■■■■■■■■■■■■■■
>プログラムの、L"button1";のところの
>Lというのはどういった意味があるのでしょうか?
>初歩的な質問かもしれませんが教えてほしいです。

Lの意味
Lをつけるとコンパイル時に""内の文字を変換なしで実行されるようです。
Lをつけないときはコンパイル時に""内の文字をUnicodeへ変換してから実行されます。
■■■■■■■■■■■■■■■■■■■■■
>private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
>は、どういった動作をさせるために書いているんですか?

ボタン1(button1)を押したときに、させたいことを記述する場所です。
本稿では、ボタン1を押すことで、リストボックスに使用可能なシリアルポートを表示するようにしたものです。
()内にあるのは引数(ひきすう)と呼ばれるものです(とりあえずは使う必要はないと思います)。

■■■■■■■■■■■■■■■■■■■■■
大変失礼なことをお聞きして申し訳ありませんが、
VC++2005/2008 は少し敷居が高いと感じているのではないでしょうか?
VC++2005/2008 という言語は、「C言語」と「C++」の経験が無いとなかなか難しいと思います。
だからといって、「C言語」から勉強するというのも大変ですよね。
でもやはり、「C言語」と「C++」の基本は習得しておいたほうが良いと思います。

私の場合ですが、初心者の頃は以下のサイトの「C言語」と「C++」を活用させていただきました。
毎日1時間程度、サンプルを入力して動かして、という勉強をしていました。
すると、2、3ヶ月で基本がマスターできました。参考まで。

http://www.geocities.jp/ky_webid/index.html
http://wisdom.sakura.ne.jp/programming/

VC#2005/2008 シリアルポートを使用する

VC#2005/2008 シリアルポートを使用する

ボタン1を押すと、listBox1に全ポート名、listBox2に使用可能なポート名を表示します。

[ツールボックス]->[コンポーネント]->[SerialPort]を貼り付けて、以下のソースを使用します。
//------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports; // シリアルポート

namespace at3200
{
public partial class Form1 : Form
{
SerialPort port; // シリアルポート宣言

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear(); // リスト1初期化
foreach (string name in SerialPort.GetPortNames())
{
listBox1.Items.Add(name); // ポート名を追加する
}

listBox2.Items.Clear(); // リスト2初期化
for (int ii = 0; ii < listBox1.Items.Count; ii++)
{
string name = ""; // ポート名初期化
try
{
name = listBox1.Items[ii].ToString(); // ポート名取得
port = new SerialPort(name);
port.Open(); // ポートオープン
}
catch (System.Exception err)
{
System.Console.WriteLine(err.Message);
name = ""; // ポート名消す
}
finally
{
port.Close(); // ポートクローズ
if (name.CompareTo("") != 0)
{
listBox2.Items.Add(name); // ポート名追加
}
}
}
}
}
}
//------------------------------------------------------------

2008年4月14日月曜日

VC++2005/2008 で Managed DirectX の環境を設定する方法

VC++2005/2008 で Managed DirectX の環境を設定する方法

とりあえず、JOYSTICKが使用できる環境を設定します。

(1)DirectX SDK と Microsoft プラットフォーム SDK をインストールする。
(2)ツール -> オプション -> VC++ディレクトリ で以下の設定を行う。
●ディレクトリを表示するプロジェクト(S):実行可能ファイル
C:\Program Files\Microsoft DirectX SDK(November 2007)\Utilities\Bin\x86
C:\Program Files\Microsoft Platform SDK\Bin
●ディレクトリを表示するプロジェクト(S):インクリュードファイル
C:\Program Files\Microsoft DirectX SDK(November 2007)\Utilities\Include\x86
C:\Program Files\Microsoft Platform SDK\Include
●ディレクトリを表示するプロジェクト(S):ライブラリファイル
C:\Program Files\Microsoft DirectX SDK(November 2007)\Utilities\Lib\x86
C:\Program Files\Microsoft Platform SDK\Lib

(3)ソリューションエクスプローラーのプロジェクト名で右クリック -> 参照 -> 新しい参照の追加で以下を追加する。
●Microsoft.DirectX
●Microsoft.DirectX.DirectInput
●その他、DirectXで使用したいものがあれば追加する

(4)form1.hで以下を宣言する。
using namespace Microsoft::DirectX;
using namespace Microsoft::DirectX::DirectInput;

2008年4月5日土曜日

VC#2005/2008 string型を数値に変換する方法(変換失敗にも対応)

VC#2005/2008 string型を数値に変換する方法(変換失敗にも対応)
変換できる場合のみ変換します。

■C++
int result;
int::TryParse( textBox1->Text , result );

■C#
int result;
int.TryParse(textBox1.Text , out result);

2008年3月22日土曜日

VC#2005/2008 pictureBox jpgファイルを表示する方法

VC#2005/2008 pictureBox jpgファイルを表示する方法

■pictureBox にjpgファイルを表示する
//------------------------------------------
pictureBox1.BackgroundImage = Image.FromFile(@"C:\picture\same.jpg");
//------------------------------------------

■pictureBox にjpgファイルを背景を透明にして表示する
//------------------------------------------
Bitmap bitmap = new Bitmap(pib[iii].jpgName);
bitmap.MakeTransparent();
pictureBox1.BackgroundImage = bitmap;
//------------------------------------------

2008年3月10日月曜日

VC#2005/2008 pictureBox を移動させる方法

VC#2005/2008 pictureBox を移動させる方法

■pictureBox を移動させる方法
pictureBox を移動させるには、Point変数を宣言し、そこに移動させたい座標を代入して Location にセットします。

//------------------------------------------
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

Point poi; // 宣言

private void button1_Click(object sender, EventArgs e)
{
poi = pictureBox1.Location; // 現在の座標取得
poi.X++; // X座標++
pictureBox1.Location = poi; // pictureBox に反映する
}
}
}
//------------------------------------------

2008年2月18日月曜日

VC++2005 unsigned char*型 から string型へ変換する方法

VC++2005 unsigned char*型 から string型へ変換する方法

■unsigned char*型 から string型へ変換する方法
//------------------------------------------
using namespace std;

unsigned char buf[] = "あいうえお";
unsigned char* str = buf;

string sss = string((char*)str); // string型へ変換
//------------------------------------------

2008年2月15日金曜日

VC#/VC++2005 テキストボックス1の数値を16進数に変換してテキストボックス2に表示する

VC#/VC++2005 テキストボックス1の数値を16進数に変換してテキストボックス2に表示する

■VC#2005の場合
textBox2.Text = String.Format("{0:X}",Convert.ToInt16(textBox1.Text));
■VC++2005の場合
textBox2->Text = ::String::Format("{0:X}",::Convert::ToInt16(textBox1->Text));

コンバートの種類は ToByte , ToChar , ToInt32 など他にもいろいろあります。

2008年2月12日火曜日

VC#2005 フォームをシングルトンのモードレスにする方法

VC#2005 フォームをシングルトンのモードレスにする方法

フォームのインスタンスがすでに存在するかどうかチェックし、なければ新しいインスタンスを作成するようにします。
VC++2005より簡単です。

//■form1.cs
private void button1_Click(object sender, EventArgs e)
{
Form2.Instance().Show();
}
//■form2.cs
public partial class Form2 : Form
{
/* コメントにする↓
public Form2()
{
InitializeComponent();
}
コメントにする↑ */

// 追加する ↓
private static Form2 instance = new Form2();

public static Form2 Instance()
{
if (instance.IsDisposed)
{
instance = new Form2();
}
Form2.instance.InitializeComponent();
return instance;
}
// 追加する ↑
}

2008年2月5日火曜日

VC++2005 ファイルのドラッグ&ドロップの実装(訂正)

VC++2005 ファイルのドラッグ&ドロップの実装(訂正)

08/02/04 の記事に間違いがありましたので、訂正したもの記載します。

エクスプローラからファイルをドラッグしてテキストボックスにドロップすると
ファイル名を表示する方法です。

//-------------------------------------------------------------------
private: System::Void textBox1_DragEnter(System::Object^ sender, System::Windows::Forms::DragEventArgs^ e) {
if(e->Data->GetDataPresent(DataFormats::FileDrop))
{
e->Effect = DragDropEffects::All;
}
else
{
e->Effect = DragDropEffects::None;
}
}
//-------------------------------------------------------------------
private: System::Void textBox1_DragDrop(System::Object^ sender, System::Windows::Forms::DragEventArgs^ e) {
if(e ->Data ->GetDataPresent(DataFormats::FileDrop)) // ファイルドロップのとき
{
array<System::String^>^ files = // 列挙型のファイル名を一覧を取得する
static_cast<array<System::String^>^>
(e->Data->GetData(DataFormats::FileDrop , false));
this->textBox1->Text = files[0]; // 先頭ファイル出力
}
}
//-------------------------------------------------------------------
※上記ソースはそのままコピーして使用するとコンパイルエラーとなります。
全角'<'を半角'<'すれば大丈夫です。

2008年2月4日月曜日

VC++2005 ファイルのドラッグ&ドロップの実装

VC++2005 ファイルのドラッグ&ドロップの実装

エクスプローラからファイルをドラッグしてテキストボックスにドロップすると
ファイル名を表示する方法です。

//-------------------------------------------------------------------
private: System::Void textBox1_DragEnter(System::Object^ sender, System::Windows::Forms::DragEventArgs^ e) {
if(e->Data->GetDataPresent(DataFormats::FileDrop))
{
e->Effect = DragDropEffects::All;
}
else
{
e->Effect = DragDropEffects::None;
}
}
//-------------------------------------------------------------------
private: System::Void textBox1_DragDrop(System::Object^ sender, System::Windows::Forms::DragEventArgs^ e) {
if(e ->Data ->GetDataPresent(DataFormats::FileDrop)) // ファイルドロップのとき
{
array^ files = // 列挙型のファイル名を一覧を取得する
static_cast<array<System::String^>^>
(e->Data->GetData(DataFormats::FileDrop , false));
this->textBox1->Text = files[0]; // 先頭ファイル出力
}
}
//-------------------------------------------------------------------

2008年1月26日土曜日

VC++2005 フォームをシングルトンのモードレスにする方法

VC++2005 フォームをシングルトンのモードレスにする方法

フォームのインスタンスを静的フィールドに保持しておき、nullのときは新しいインスタンスを作成するようにします。ボタンを押すと、Form2 のインスタンスに対して Show() します
詳細は以下に示します。

//-----------------------------------------------
// 親ウィンドウ Form1.h ボタンを押したとき
// button1 を押すと Form2 を表示します
//-----------------------------------------------
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
Form2::Instance()->Show();
}
//-----------------------------------------------
// 子ウィンドウ Form2.h のコンストラクタ部
//-----------------------------------------------
public ref class Form2 : public System::Windows::Forms::Form
{
public:
//*********** 追加 ↓ ***********
static Form2^ Instance()// インスタンスの生成を行う静的メンバ関数
{
if(_instance == nullptr){
_instance = gcnew Form2;
}
return _instance;
}
//*********** 追加 ↑ ***********
public:
Form2(void)
{
InitializeComponent();
//
//TODO: ここにコンストラクタ コードを追加します
//
}
//-----------------------------------------------
// 子ウィンドウ Form2.h のメンバ変数宣言部(静的)
// 必要なデザイナへインスタンス変数を追加します
//-----------------------------------------------
private:
static Form2^ _instance; // インスタンス変数
//-----------------------------------------------
// 子ウィンドウ Form2.h の×を押したとき
// Form2 のインスタンス変数も初期化します
//-----------------------------------------------
private: System::Void Form2_FormClosed(System::Object^ sender, System::Windows::Forms::FormClosedEventArgs^ e) {
_instance = nullptr;
}
//-----------------------------------------------

2008年1月23日水曜日

VC++2005 ボタンをオルタネート動作にする方法

VC++2005 ボタンをオルタネート動作にする方法

ボタンをオルタネート動作にするには、チェックボックスを使用すると簡単に行えます。

■プロパティを変更します。
Appearance = "Button"

■ボタンを押したときボタンの色を変更します。
private: System::Void checkBox1_CheckedChanged(System::Object^ sender, System::EventArgs^ e) {
if( checkBox1->Checked == true )
{
checkBox1->BackColor::set(Color::Green);
}
else
{
checkBox1->BackColor::set(Color::WhiteSmoke);
}