首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ Builder 實用程式碼片段大全

     編輯:關於C++

開發過程中累積的常用程式碼片段往往能事半功倍。本文整理了 C++ Builder 開發中高頻使用的 15 個實用片段,涵蓋資料庫操作、類別設計、UI 控制、字串處理、系統整合等領域,供開發者快速參考與複用。

資料庫操作篇

1. 刪除指定別名下所有資料表

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;
}

2. 檢查資料表是否存在(以 Paradox 為例)

#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;

3. 檢查元件中是否有處於編輯狀態的 TTable

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();
            }
        }
    }
}

4. 遍歷資料表記錄並填入字串列表

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); }
}

類別與物件導向篇

5. 純虛函數與多型示範

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"

6. 虛函數與基類指標陣列

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();

UI 與系統整合篇

7. 啟動畫面實作

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;
}

8. 剪貼板文字讀取

#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());
}

9. 字串流格式化輸出

#include <sstream>
const char *name = "cker", *email = "cker@sina.com";
std::ostringstream ost;
ost << "\"" << name << "\"[SMTP:" << email << "]";
Edit1->Text = ost.str().c_str();

10. 取得元件類別名稱(偵錯用)

for (int i = 0; i < ComponentCount; i++)
    if (dynamic_cast<TComponent>(*Components[i]).Name == "")
        ShowMessage(Components[i]->ClassName());

11. 改變 PageControl 標籤狀態

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;
    }
}

12. 繪製自訂狀態列面板

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;
    }
}

工具與基礎語法篇

13. 指標基本操作

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

14. 變數與常數宣告範例

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; };

15. 向 TQuery 傳遞參數與日期運算

// 參數化刪除
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);
}

這些片段皆源自實戰專案,建議建立個人程式碼庫並依功能分類管理,隨用隨取,持續精進。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved