開發過程中累積的常用程式碼片段往往能事半功倍。本文整理了 C++ Builder 開發中高頻使用的 15 個實用片段,涵蓋資料庫操作、類別設計、UI 控制、字串處理、系統整合等領域,供開發者快速參考與複用。
void TData::CleanTemp()
{
TStringList *myTables = new TStringList();
TTable *Table = new TTable(this);
try
{
Session->GetTableNames("Temp", "", True, False, myTables);
}
catch (...) {}
for (int count = 0; count < myTables->Count; count++)
{
Table->DatabaseName = "Temp";
Table->TableName = myTables->Strings[count];
Table->Close();
Table->DeleteTable();
}
delete myTables;
delete Table;
}
#include <io.h>
if (access(Table1->TableName.c_str(), 0)) // 不存在則建立
{
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;
void TData::CheckEdit()
{
for (int i = 0; i < ComponentCount; i++)
{
if (dynamic_cast<TTable*>(Components[i]))
{
if (((TTable*)Components[i])->State == dsEdit)
{
String s = "Table " + Components[i]->Name + " is in edit mode\r\nPost before 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 TDataModuleEmployee::ListNames(TStrings *Items)
{
try
{
for (TableAll->First(); !TableAll->Eof; TableAll->Next())
if (!TableAll->FieldByName("Deleted")->AsBoolean)
Items->AddObject(TableAll->FieldByName("Name")->AsString,
(TObject*)TableAll->FieldByName("Refnum")->AsInteger);
}
catch (Exception &e) { Application->ShowException(&e); }
}
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"); } };
// 使用範例
TDerivedClass dc; dc.Display(); // "From Derived"
TSecondDerivedClass sc; TBaseClass* bc = ≻ 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();
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
SplashForm = new TSplashForm(Application);
SplashForm->Show(); SplashForm->Update();
Application->Initialize();
Application->Title = "Loading Splash Form";
Application->CreateForm(__classid(TMainForm), &MainForm);
Application->CreateForm(__classid(TDataModule), &DataModule);
Application->CreateForm(__classid(TAboutBox), &AboutBox);
SplashForm->Hide(); SplashForm->Close();
Application->Run();
}
catch (Exception &exception) { Application->ShowException(&exception); }
return 0;
}
#include <memory> #include <clipbrd.hpp>
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner)
{
std::auto_ptr<TStringList> ClipText(new TStringList);
ClipText->Text = Clipboard()->AsText;
Memo1->Lines->AddStrings(ClipText.get());
}
#include <sstream>
const char *name = "cker", *email = "cker@sina.com";
std::ostringstream ost;
ost << "\"" << name << "\"[SMTP:" << email << "]";
Edit1->Text = ost.str().c_str();
for (int i = 0; i < ComponentCount; i++)
if (dynamic_cast<TComponent>(*Components[i]).Name == "")
ShowMessage(Components[i]->ClassName());
void __fastcall TfmMainForm::Cancel1Click(TObject *Sender)
{
int i;
switch (PageControl1->ActivePage->Tag)
{
case 1: case 2:
for (i = 0; i < ComponentCount; i++)
if (dynamic_cast<TEdit>(Components[i]))
dynamic_cast<TEdit>(Components[i])->Enabled = false;
Data->tbDetail->Cancel(); break;
case 3:
for (i = 0; i < ComponentCount; i++)
if (dynamic_cast<TEdit>(Components[i]))
dynamic_cast<TEdit>(Components[i])->Text = "";
break;
}
}
void __fastcall TForm1::StatusBar1DrawPanel(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, MAKEINTRESOURCE(32760));
c.Draw(Rect.Left, Rect.Top, bm);
delete bm;
break;
}
}
int array[] = {2,4,6,8,10};
int* myPtr = array;
int myInteger = myPtr[3]; // 8
int x = 32; int* ptr = &x;
int y = *ptr; // 解除參考,y = 32
char ch; int count = 1; char* name = "csdn.net";
struct complex { float my, his; };
float real(complex* p) { return p->my; }
const double pi = 3.1415926535897932385;
template<class T> T abc(T a) { return a < 0 ? -a : a; }
enum WebSite { one, two, three, four };
int* a; char* p[20]; void myFunction(int);
struct str { short length; char* p; };
// 參數化刪除
TQuery *Query = new TQuery(this);
Query->DatabaseName = "dbServer";
Query->SQL->Clear();
Query->SQL->Add("DELETE FROM 'Events.DB' WHERE (TicketNo = " + Data->tbProblem->FieldByName("TicketNo")->AsString + ")");
Query->ExecSQL(); Query->Close(); delete Query;
// 日期屬性運算
void __fastcall TfmMainForm::CountOpen(TObject *Sender)
{
switch (dynamic_cast<TComponent>(*Sender).Tag)
{
case 1: count1 = StrToInt(lbCount1->Caption); count1++; Date2 = Now() + count1; break;
case 2: count1 = StrToInt(lbCount1->Caption); count1--; Date2 = Now() + count1; break;
}
meOpen->Text = Date2.DateString(); lbCount1->Caption = IntToStr(count1);
}
這些片段皆源自實戰專案,建議建立個人程式碼庫並依功能分類管理,隨用隨取,持續精進。