C++Builder常用程式碼片斷 (轉)

worldblog發表於2007-12-05
C++Builder常用程式碼片斷 (轉)[@more@]microsoft FrontPage 4.0">

和事件" href="to:cker@sina.com">C++Builder程式碼片斷

本文中包含了一些常用的程式碼片斷,看看想想或許有他山之石可以攻玉的可能。 CKER

的類名">元件的類名

 


void TData::CleanTemp() 

  TStringList *myTables = new TStringList();
  TTable *Table = new TTable(this);
  try
  { 
  Session->GetTableNames("Temp", "", True, False, myTables);
  }
  catch (...) {} 
// AnsiString str = myTables->GetText(); 
// ShowMessage(str); 
  for(int count=0; count < myTables->Count; count++) 
  { 
  Table->DatabaseName = "Temp";
  Table->TableName = myTables->Strings[count];
  Table->Close(); 
  Table->DeleteTable(); 
  }
  delete myTables;
  delete Table;


//純虛擬函式只在基類中出現,而在子類中必須有
//與其匹配的成員函式。中申明的子類的例項
file://必須為基類中的每一個純虛擬函式提供一個過載的成員函式。
class TBaseClass 

  public: 
  virtual void Display() = 0;
};
class TDerivedClass : public TBaseClass 

  public: 
  void Display() { ShowMessage("From Derived"); }
}; 
 
class TSecondDerivedClass : public TDerivedClass 

  public: 
  void Display() { ShowMessage("From Second Derived"); } 
}; 
 
void __fastcall TForm1::Button1Click(T *Sender) 

  TDerivedClass dc; dc.Display();// "From Derived" 
  TSecondDerivedClass sc; TBaseClass* bc = &sc; 
  bc->Display(); // "From Second Derived" 



//虛擬函式作為其他類的父類的成員函式。
//如果繼承子類成員函式中存在與父類成員函式完全相同的函式,
//子類中的成員函式永遠有效。

class Base 
{
 public: 
  virtual void Display() { ShowMessage("Base Class"); }
};
 
class DerivedOne : public Base 

  public: 
  void Display() { ShowMessage("DerivedOne"); } 
}; 
 
class DerivedTwo : public Base 

  public: 
  void Display() { ShowMessage("DerivedTwo"); } 
};
 
Base* pBases[10];
int count = 0;
DerivedOne aDerOne;
DerivedTwo aDerTwo;
pBases[count++] = &aDerOne;
pBases[count++] = &aDerTwo;
for( int i=0; i < count; i++ )
pBases[i]->Display(); 


USEDATAMODULE("Datamod.cpp", DataModule);
USEFORM("about.cpp", AboutBox);
USEFORM("main.cpp", MainForm);
USEFORM("splash.cpp", SplashForm);
file://--------------------------------------------------------------------------- 
#include "splash.h"
WIN WinMain(HINSTANCE, HINSTANCE, LPSTR, int) 
{
  try 
  { 
  SplashFo= new TSplashForm(Application);
  SplashForm->Show(); 
  SplashForm->Update();
  Application->Initialize();
  Application->Title = "Example of Loading Splash Form"; 
  Application->HelpFile = "SplashHelp.hlp"; 
  Application->CreateForm(__classid(TMainForm), &MainForm); 
  Application->CreateForm(__classid(TDataModule), &DataModule); 
  Application->CreateForm(__classid(TAboutBox), &AboutBox);
  SplashForm->H(); 
  SplashForm->Close(); 
  Application->Run(); 
  }
  catch (Exception &exception) 
  { 
  Application->ShowException(&exception);
  }
  return 0;
}


int array[] = { 2, 4, 6, 8, 10}
int myInteger = array[3]; // 值為 8
 
// ----使用指標可以實現同樣的功能 ----- 
int array[] = { 2, 4, 6, 8, 10}
int* myPtr = array;
int myInteger = myPtr[3]; // 值為8 
int x = 32;
int* ptr = &x; 
//解除指標的引用
file://以獲得位置的內容

int y = *ptr; // y = 32 


void TDataModuleEmployee::ListNames( TStrings *Items )
{
 try
 {
  for ( TableAll->First(); !TableAll->Eof; TableAll->Next() )
  if ( TableAll->FielyName("Deleted")->AsBoolean == false )
  Items->AddObject( TableAll->FieldByName("Name")->AsString, (TObject *)TableAll->FieldByName("Refnum")->AsInteger );
 }
 catch (Exception &e)
 {
  Application->ShowException(&e);
 }; 




char ch;
int count = 1;
char* name = "csdn";
struct complex { float my, his;};
float real(complex* p) {return p->my};
const double pi = 3.1415926535897932385;
templetate abc(T a) { return a < 0 ? -a : a; };
enum Site { one, two, three, four};
int* a; // * 指標
char* p[20]; // [ ] 陣列 
void myFunction(int); // ( )函式 
struct str { short length; char* p; };
char ch1 = 'a'; 
char* p = &ch1; // &引用 ,p保持著ch1的地址 
char ch2 = *p; // ch2 = 'a' 


#include "io.h" 
if (access(Table1->TableName.c_str(),0)) file://檢查表是否存在 
{ // 若不存在就建立 ... 
 Table1->Active = false;
 Table1->TableType = ttParadox;
 Table1->FieldDefs->Clear();
 Table1->FieldDefs->Add("Myfield", ftString, 15, false);
 Table1->IndexDefs->Clear();
 Table1->CreateTable(); 
 Table1->Active = true;
}
else
 Table1->Active = true; 


//找出丟失的元件類名
for(int i=0; i < ComponentCount; i++) 
{
 if(String(dynamic_cast(*Components[i]).Name) == "") 
 { 
  ShowMessage(Components[i]->ClassName());
 }




#include "memory.h" // 包含 auto_ptr<> 
#include "clipbrd.hpp" file://包含 TClipboard & Clipboard()
// 範例程式,包含了一個memo 
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{ file://建立 TStringList 
auto_ptr ClipText(new TStringList); file://得到剪貼簿中的文字的複製 
ClipText->Text = Clipboard()->AsText; file://然後加工一下... 
Memo1->Lines->AddStrings(ClipText.get()); 



//範例一
#include "sstream" 
const char *name = "cker";
const char * = "cker@sina.com";
// 生成 "cker"[SMTP:cker@sina.com] 
 
ostringstream ost;
ost << """ << name << ""[SMTP:" << email << "]";
Edit1->Text = ost.str().c_str();
 
file://範例二
void TDataModuleEmployee::FullReport(const char *title)
{
Report.header(title);
Report << ormat( "Employee #%2d: %s%sn", TableAllRefnum->Value, TableAllName->Text.c_str(), 
TableAllManagerFlag->Value ?"(Manager)" : "" ) << " Address: " <TableAllAddress->Text.c_str() << endl << " " << TableAllCityProvZip->Text.c_str() <<
endl << " " << NameCountry(TableAllCanada->Value) << endl;
Report.footer();



void TData::CheckEdit()
{
 for(int i=0; i < ComponentCount; i++)
 { 
  if(dynamic_cast(Components[i]))
  {
  if(((TTable*)Components[i])->State == dsEdit)
  {
  String s = "Table " + Components[i]->Name + " is in edit mode" "rWould you like to post it before entering new task?";
  if(MessageBox(NULL,s.c_str(),"Table in Edit Mode",MB_YESNO | MB_ICONINFORMATION) == IDYES)
  ((TTable*)Components[i])->Post(); else ((TTable*)Components[i])->Cancel();
  }
  }
 }



//關閉已開啟的表並將他們恢復成初始狀態。
void TData::MyTables(TForm * sender)
{
 int i;
 TTable * Table;
 bool *active = new bool[MyClass->ComponentCount];//在動態陣列中存放每個表的初始狀態,然後關閉所有的表
 for(i = 0; i < MyClass->ComponentCount; i++)
  {
  try
  {
  if((Table = dynamic_cast(MyClass->Components[i])) != NULL)
  {
  active[i] = Table->Active;
  Table->Active = false;
  }
  }
  catch(...) {}; file://異常應該只來自於dynamic cast...
  }
 for(i = 0; i < MyClass->ComponentCount; i++)
  {
  try
  {
  if((Table = dynamic_cast(MyClass->Components[i])) != NULL)
  { 
  if(Table->DatabaseName != OPTARDatabase->DatabaseName)
  continue;
  DBIResult result = DBIERR_NONE + 1;
  while(result != DBIERR_NONE) file://若希望的話,這樣允許重試!
  {
  result = DbiPackTable (OPTARDatabase->Handle,NULL,Table->TableName.c_str(),NULL, true);
  if(result != DBIERR_NONE)
  { 
  AnsiString rsltText = "Unable to pack " + Table->TableName + "." ;
  char rslt[DBIMAXMSGLEN + 1];
  DbiGetErrorString(result, rslt) rsltText += ". Try again?";
  if(Application->MessageBox(rsltText.c_str(), "Error!",MB_YESNO) != IDYES)
  break; 
  }
  }
  }
  }
  catch (...) {}; file://異常應該只來自於dynamic cast...
  }
 // 將所有的表設回初始狀態。
 for(i = 0; i < MyClass->ComponentCount; i++)
  {
  try
  {
  if((Table = dynamic_cast(MyClass->Components[i])) != NULL) 
  Table->Active = active[i];
  }
  catch(...) {};
  }
 delete []active;


void __fastcall TfmMainForm::Cancel1Click(TObject *Sender)
{
 int i;
 switch (PageControl1->ActivePage->Tag))
  {
  case 1:
  for (i=0; i < ComponentCount; i++)
  {
  if (dynamic_cast(Components[i]))
  dynamic_cast(Components[i])->Enabled = false;
  }
  Data->tbDetail->Cancel();
  break;
  case 2:
  for (i=0; i < ComponentCount; i++)
  {
  if (dynamic_cast(Components[i]))
  dynamic_cast(Components[i])->Enabled = false;
  }
  Data->tbDetail->Cancel();
  break;
  case 3:
  for (i=0; i < ComponentCount; i++)
  {
  if (dynamic_cast(Components[i]))
  dynamic_cast(Components[i])->Text = "";
  }
  break;
  }




// 直接從表向Query傳遞引數的一種方法
TQuery *Query = new TQuery(this);
Query->DatabaseName = "dbServer";
Query->->Clear();
Query->SQL->Add("DELETE FROM 'Events.DB' WHERE (TicketNo = " + Data->tbProblem->FieldByName("TicketNo")->AsString + ")" );
Query->ExecSQL();
Query->Close();
delete Query; 



TMaskEdit *meOpen;
TLabel *lbCount1;
TDateTime Date2;
void __fastcall TfmMainForm::CountOpen(TObject *Sender)
{
 switch(dynamic_cast(*Sender).Tag)
  {
  case 1:
  count1 = StrToInt(lbCount1->Caption);
  count1 += 1;
  Date2 = Now() + count1;
  meOpen->Text = Date2.DateString();
  lbCount1->Caption = IntToStr(count1);
  break;
  case 2:
  count1 = StrToInt(lbCount1->Caption);
  count1 -= 1;
  Date2 = Now() + count1;
  meOpen->Text = Date2.DateString();
  lbCount1->Caption = IntToStr(count1);
  break;
  }




void __fastcall TForm1::Statar1DrawPanel(TStatusBar *StatusBar, TStatusPanel *Panel, const TRect &Rect)
{
 TCanvas& c = *StatusBar->Canvas;
 switch (Panel->Index)
  {
  case 0 :
  {
  StatusBar1->Panels->Items[0]->Text = "Hello C++";
  c.Brush->Style = bsClear;
  TRect temp = Rect;
  temp.Top += 1;
  temp.Left += 1; 
  c.Font->Color = clWhite;
  DrawText(c.Handle, Panel->Text.c_str(), -1,(RECT*)&temp, DT_SINGLELINE | DT_CENTER);
  c.Font->Color = clBlack;
  DrawText(c.Handle, Panel->Text.c_str(), -1, (RECT*)&Rect, DT_SINGLELINE | DT_CENTER);
  break;
  }
  case 1:
  {
  c.Brush->Color = clYellow;
  c.FillRect(Rect);
  c.Font->Color = clRed;
  DrawText(c.Handle,"clYellow Color", -1, (RECT*)&Rect, DT_SINGLELINE | DT_CENTER);
  break;
  }
  case 2:
  {
  Graphics::TBitmap* bm = new Graphics::TBitmap;
  bm->Handle = LoadBitmap(NULL, MAKEINTRE(32760));
  c.Draw(Rect.Left, Rect.Top, bm);
  delete bm;
  break;
  }
  }
}
 


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-988740/,如需轉載,請註明出處,否則將追究法律責任。

相關文章