Create Insert Table menu like in Word using TDrawGrid component (Views: 27)
Problem/Question/Abstract: I think all of us know the function in MS Word which is called "Insert Table". Pressing this button there appears SubMenu window which is separated in squares - cells and columns. When we move a mouse on these squares they become active and after pressing left mouse button is create the table with the same number of cells and columns as we selected. Maybe anyone could suggest how to do this. Answer: The solution is Put TDrawGrid component on Form and name it dwgTable, then property DefaultDrawing set to false. Also configure the following properties: DefaultColWidth to 20 DefaultRowHeight to 15 ColCount first set to 0 then 3 RowCount first set to 0 then 3 BorderStyle to bsNone Schroolbar also to none The code is procedure TForm1.dwgTableMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var vCol, vRow: Integer; begin if (X > 0) and (y > 0) then begin vCol := Trunc(x / (dwgTable.DefaultColWidth + 1)); vRow := Trunc(y / (dwgTable.DefaultRowHeight + 1)); dwgTable.ColCount := vCol + 2; dwgTable.RowCount := vRow + 2; end; dwgTable.Height := (dwgTable.DefaultRowHeight + 1) * dwgTable.RowCount; dwgTable.Width := (dwgTable.DefaultColWidth + 1) * dwgTable.ColCount; end; procedure TForm1.dwgTableDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); var vColText, vRowText: string; RowHorzOffset, RowVertOffset, ColHorzOffset, ColVertOffset: integer; begin if (dwgTable.ColCount - 1 = ACol) or (dwgTable.RowCount - 1 = ARow) then begin dwgTable.Canvas.Brush.Color := clInfoBk; dwgTable.Canvas.FillRect(Rect); vColText := Inttostr(ACol + 1); vRowText := Inttostr(ARow + 1); with dwgTable.Canvas do begin RowVertOffset := (((Rect.Bottom - Rect.Top) - TextExtent(vRowText).CY) div 2); RowHorzOffset := ((Rect.Right - Rect.Left) - TextExtent(vRowText).CX) div 2; ColVertOffset := (((Rect.Bottom - Rect.Top) - TextExtent(vColText).CY) div 2); ColHorzOffset := ((Rect.Right - Rect.Left) - TextExtent(vColText).CX) div 2; end; if (dwgTable.ColCount - 1 <> ACol) or (dwgTable.RowCount - 1 <> ARow) then begin if (dwgTable.ColCount - 1 = ACol) then dwgTable.Canvas.TextOut(Rect.Left + RowhorzOffset, Rect.Top + RowVertOffset, vRowText); if (dwgTable.RowCount - 1 = ARow) then dwgTable.Canvas.TextOut(Rect.Left + ColhorzOffset, Rect.Top + ColVertOffset, vColText); end; end else begin dwgTable.Canvas.Brush.Color := clWindow; dwgTable.Canvas.FillRect(Rect); end; end; procedure TForm1.dwgTableClick(Sender: TObject); begin ShowMessage('Col:' + Inttostr(dwgTable.ColCount - 1) + ' Row: '+Inttostr(dwgTable.RowCount-1)); end; |