Delphi 在窗體上建立自己遊標的實例
我們知道在文字方塊等可以接收輸入的元件中,我們可以看到閃爍的遊標,並且可以輸入文字,如果我們在,例如窗體上時,因為不支援輸入,也無法顯示閃爍的遊標,那我們有辦法做自己的輸入嗎?當然可以,下面我們示範在Form上來輸入文字。
用到的API函數如下
Delphi程式碼
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); Char); procedure FormPaint(Sender: TObject); private { Private declarations } s:string; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TtricObject);存放字型資訊tm:TTextMetric; begin s := ''; GetTextMetrics(Self.Canvas.Handle,tm); { 注意CreateCaret 的第二個參數是HBITMAP類型,所以你可以使用自己的圖形作為遊標形狀,這裡採用預設後面兩個參數是遊標的寬度和高度,可以自定義} CreateCaret(Self.Handle,HBITMAP(nil),tm.tmAveCharWidth div 2,tm.tmHeight); ShowCaret(Self.Handle); //在(10,,10)這個點上顯示SetCaretPos(10,10); end; //窗體按鍵事件,每次按一個鍵後,重寫s的值,在OnPaint事件中會把s的值畫到窗體上procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char); begin //如果是退格鍵,則刪除前一個字元if Ord(Key) = VK_BACK then begin if (s <> '') then Delete(s,Length(s),1); end else s := s + Key; //重繪Self.Invalidate; end; procedure TForm1.FormPaint(Sender: TObject ); begin Self.Canvas.TextOut(10,10,s); //重新設定遊標位置SetCaretPos(Self.Canvas.TextWidth(s)+10,10); end; end.VC程式碼
//全域字串變數CString s; //初始化時,設定遊標BOOL CTest_MFCDlg::OnInitDialog() { CDialog::OnInitDialog(); ShowSelfCaret(); ...... } //為表單新增函數,初始化遊標void CTest_MFCDlg::ShowSelfCaret(void) { CClientDC dc(this); TEXTMETRIC tm; dc.GetTextMetrics(&tm); CreateSolidCaret(tm.tmAveCharWidth/2,tm.tmHeight); ShowCaret(); POINT p; px = 0; py = 0; SetCaretPos(p); } //重載PreTranslateMessage BOOL CT_MFMF PreTranslateMessage(MSG* pMsg) { //如果是按鍵按下if (pMsg->message == WM_KEYDOWN) { //如果是退格鍵,刪除結尾字元if (pMsg->wParam == VK_BACK) { if (s.GetLength() != 0) { s.Delete(s. GetLength() - 1,1); } } else //追加字元s.Insert(s.GetLength(),(TCHAR)pMsg->wParam); Invalidate(true); } return CDialog::PreTranslateMessage(pMsg); } //自畫,將s的內容畫到窗體上void CTest_MFCDlg::OnPaint() { CPaintDC dc(this); CRect rect; GetClientRect(&rect); CSize size = dc.GetTextExtent(s); POINT p; px = size.cx; py = 0; SetCaretPos(p); dc.DrawText(s,s.GetLength(),rect,DT_LEFT); }如有疑問請留言或到本站社區交流討論,感謝閱讀,希望能幫助大家,謝謝大家對本站的支持!