Page 1 sur 1

Création de fonctions tableau

Publié : sam. 23/avr./2011 12:29
par dayvid
Bonjour, j'ai commencer a crée des fonctions pour gérer un tableau
mais je me demande si sa n'existe pas déjà

Quoi qu'il en soit je démarre plutôt bien :)

Code : Tout sélectionner

; Crée par Monsieur Dieppedalle David le 22 avril

Global NewList MesTableau.s() ; Les tableaux ainsi que toutes leurs données vont-être enregistrer dans cette liste chainée

Global *MemoireID = AllocateMemory(1) ; J'initialise l'adresse de la mémoire
Global *Pointeur = *MemoireID ; Je mémorise l'adresse de la memoire pour plus tard ajouté et lire des données

If *MemoireID ; Si l'allocation a bien fonctionné, tous va bien !
Else
  Debug "Impossible d'allouer la mémoire demandée !"
EndIf 

; Cette procedure servira pour y ajouté les données du tableau
Procedure AjoutDonnerMemoire(Donner$)
CopyMemoryString(PeekS(*Pointeur, -1, #PB_Ascii) + Donner$, @*Pointeur)
EndProcedure

Procedure.s CreeTableau(NomTableau$, NombreColonne, TailleColonne, NombreLigne, Chaine$) ; Crée un tableau avec le nombre de ligne et de colonne et taille des colonne indiquer puis remplie chaque élement avec la chaine, sa permet d'initialiser tous les élements du tableau
  
  ; J'aloue la mémoire néccessaire pour y introduire le tableau, je fait sa avec la mémoir pour que sa ail hyper vite !
  *MemoireID = AllocateMemory(100000000) ; Y'aura surement du gaspillage de mémoire mais je préfère voir trop grand que pas asser (100 Mo)
  *Pointeur = *MemoireID ; Je mémorise l'adresse de la memoire pour plus tard ajouté et lire des données
  
  If *MemoireID ; Si la mémoire est valide
  Else
    Debug "Impossible d'allouer la mémoire demandée !"
    ProcedureReturn Str(0) ; Sinon je quitte la procedure
  EndIf 
  
  If Trim(NomTableau$) <> "" ; Si un nom a été donner pour le tableau
    NomTableau$ = Trim(NomTableau$) ; J'enlève tous les éspace au début et a la fin du nom du tableau pour évité les erreur
    
    ; Je vais passer en revue chaque tableau de la liste
    ForEach MesTableau()
      ; j'éxtrait le nom du tableau en court de lecture
      VerrificationNomTableau$ = Trim(StringField(MesTableau(), 1, "|")) ; J'enlève les éspace si il en à
      VerrificationNomTableau$ = RemoveString(VerrificationNomTableau$, " =", 1, 1); Je supprime le " =" apres le nom du tableau pour la vérrification ou sinon sa fausse tous
      
      If NomTableau$ <> VerrificationNomTableau$ ; Si le nom du tableau est diffèrent du nom donner
        ; Tous va bien, le tableau n'éxiste pas
      Else
        ; Sinon, le tableau éxiste déjà donc ont igniore tous simplement la commande
        Debug "Le tableau: " + Chr(34) + NomTableau$ + Chr(34) + " éxiste déjà !"
        ProcedureReturn Str(0) ; je quitte la procedure
      EndIf
      
    Next MesTableau()
    
  Else ; Sinon si aucun nom de tableau n'as été donnée, nous allone crée automatiquement le nom de celui-ci suivent le nombre de tableau présent dans la liste
    If ListSize(MesTableau()) > 0 ; Si la liste comptien au moins un tableau
      NumeroTableau = ListSize(MesTableau()) + 1 ; J'incrémente de 1 le numero qui sera attribuer au nom du tableau
    Else
      NumeroTableau = 1 ; sinon si il n'y as aucun tableau dans la liste, le numéro du tableau commence a 1
    EndIf
      
    NomTableau$ = "Tableau " + Str(NumeroTableau) ; Je crée le nom du tableau automatiquement puisqu'aucun nom n'a été donner
  EndIf
  
  If NombreColonne <= 0 ; Si le tableau ne comptien aucune colonne, ce qui n'est pas possible
    NombreColonne = 1 ; Ont met une colonne
  EndIf
  
  If NombreLigne <= 0 ; Si le tableau ne comptien aucune ligne, ce qui n'est pas possible
    NombreLigne = 1 ; Et ont met une ligne
  EndIf
  
  ; Je vais crée le tabeau
  For CreationLigneTableau = 1 To NombreLigne ; Création des lignes du tableau
    
    For CreationColonneTableau = 1 To NombreColonne ; Création des colonnes du tableau
      
      If Len(Chaine$) > TailleColonne ; Si le texte de l'élement est supérieur a la taille de la colonne
        Chaine$ = Mid(Chaine$, 1, TailleColonne) ; Je tronque la chaine, sinon ont va se croire dans la jingle lol
      EndIf
      
      ; Ici je vais modeller le tableau pour que ce soit propre
      ; Toutes les colonnes auront la même grandeur, bin sinon je vous éxplique pas le chantier lol
      If CreationColonneTableau = 1 ; Quand ont as crée la première colonne
        
        If CreationLigneTableau = 1 ; Quand ont as crée la première ligne
          AjoutDonnerMemoire("|" + Chaine$ + Space(TailleColonne - Len(Chaine$))) ; Donc ont as crée la première colonne et aussi la première ligne
        Else
          AjoutDonnerMemoire(Space(Len(NomTableau$ + " = |") - 1) + "|" + Chaine$ + Space(TailleColonne - Len(Chaine$))) ; Ici je calcule la position apres le nom du tableau, pour que les colonne soivent bien rectiligne
        EndIf
        
      Else ; Sinon ce n'est plus la première colonne que l'on crée mais bien une colonne suivente
        AjoutDonnerMemoire("|" + Chaine$ + Space(TailleColonne - Len(Chaine$))) ; 
      EndIf
      
    Next
    
    ; J'ajoute une nouvelle ligne dans le tableau
    AjoutDonnerMemoire(Chr(13) + Chr(10))
  Next
  
  ; Maintenant je stoque tout le tableau entier dans la liste au nom du tableau
  AddElement(MesTableau())
  MesTableau() = NomTableau$ + " = " + PeekS(*MemoireID)
  
  ProcedureReturn NomTableau$ + " = " + PeekS(*MemoireID)
EndProcedure

Procedure AjouterLigneTableau(NomTableau$, Position, NombreLigne) ; Ajoute le nombre de ligne spécifier a partir de la position donnée, position étans le numero de la ligne
  
EndProcedure

Procedure AjouterColonneTableau(NomTableau$, NombreColonne) ; Ajoute le nombre de Colonne spécifier a partir de la position donnée, position étans le numero de la Colonne
  
EndProcedure

Procedure SupprimerLigneTableau(NomTableau$, NumeroLigne) ; Supprime une ligne complètte du tableau, les lignes suivente sont remonté d'une position
  
EndProcedure

Procedure SupprimerColonneTableau(NomTableau$, NumeroColonne) ; Supprime une Colonne complètte du tableau, les Colonne suivente sont décaler d'une position vers la gauche
  
EndProcedure

Procedure InsererElementTableau(NomTableau$, NumeroColonne, NumeroLigne, position, Element$) ; Inser l'élement a la ligne et colonne spécifier, position étans la position en caractère dans l'élément
  
EndProcedure

Procedure RechercherElementTableau(NomTableau$, Element$) ; Recherche l'élement parmie tous le tableaux
  
EndProcedure

Procedure RemplacerElementTableau(NomTableau$, NumeroColonne, NumeroLigne, Element$) ; Remplace le comptenue de l'élement par le nouvelle élement a la ligne et colonne spécifier
  
EndProcedure

Procedure EffacerElementTableau(NomTableau$, NumeroColonne, NumeroLigne) ; Efface l'élement spécifier a la ligne et colonne spécifier, l'élement sera alors vierge
  
EndProcedure

Procedure InversserElementTableau(NomTableau$, NumeroColonne1, NumeroLigne1, NumeroColonne2, NumeroLigne2) ; Inversse l'élement 1 avec l'élement 2 dans le tableau aux lignes et colonnes spécifier
  
EndProcedure

Procedure TailleElementTableau(NomTableau$, NumeroColonne, NumeroLigne) ; Renvoie la taille en caractère que fait l'élement a la ligne et colonne spécifier
  
EndProcedure

Procedure NombreLigneTableau(NomTableau$) ; Renvoie le nombre de Ligne que comptient le tableau
  
EndProcedure

Procedure NombreColonneTableau(NomTableau$) ; Renvoie le nombre de colonne que comptient le tableau
  
EndProcedure

Procedure TrierLigneTableau(NomTableau$, NumeroLigne, ModeTrie) ; Trie les élements d'une ligne entière, le mode peut être: Ordre alphabetique croissant, Ordre alphabetique décroissant, Taille
  
EndProcedure

Procedure TrierColonneTableau(NomTableau$, NumeroColonne, ModeTrie) ; Trie les élements d'une colonne entière, le mode peut être: Ordre alphabetique croissant = 1, Ordre alphabetique décroissant = 2, Taille = 3
  
EndProcedure

Procedure TrierTousTableau(NomTableau$, ModeTrie) ;  Trie les élements du tableau entier, le mode peut être: Ordre alphabetique croissant, Ordre alphabetique décroissant, Taille
  
EndProcedure

Procedure CaseElementTableau(NomTableau$, NumeroColonne, NumeroLigne, CaseElement) ; Change la case de l'élement spécifier du tableau a la ligne et colonne spécifier, Case peut-être:  Majuscule = 1 ou Minuscule = 2
  
EndProcedure


MonTableau$ = CreeTableau("", 1000, 10, 1000, "abcdefghijklmnop")
SetClipboardText(MonTableau$)

Re: Création de fonctions tableau

Publié : dim. 24/avr./2011 11:53
par Patrick88
cherche le post sur "egrid" sur le fofo anglais

Re: Création de fonctions tableau

Publié : mar. 26/avr./2011 14:43
par dayvid
Ok merci je vais chercher :P
Edit: C'est payent :oops: :cry:

Re: Création de fonctions tableau

Publié : mar. 26/avr./2011 19:05
par SPH
Dayvid, mon ptit dayvid. Tu sais que je t'apprecie. Je t'ai soutenu lors de la premiere guerre d'irak mais depuis, tu te disperses trop. En fait, tu ne sais pas quoi inventer. Tu cherches, tu cherches, mais ca viens pas. Je t'avoue que depuis quelques temps, je ne te lis plus. Je ne lis plus non plus KCC, ton frere, et tous les posts a rallonge qui ne menent a rien.
Pour que ca change, il va falloir que tu abandonnes tous tes "projets" pour te mettre a une chose simple qui te fera progresser. Ne cherche pas a faire un logiciel de programmation. Cherche plutot a faire un petit jeu sympa ! Un jeu comme puredash ou bien un pacman, ou encore un quelconque jeu de plateau. Ca, ca te fera progresser...

Re: Création de fonctions tableau

Publié : mer. 27/avr./2011 10:14
par Patrick88
dayvid a écrit :Ok merci je vais chercher :P
Edit: C'est payent :oops: :cry:
ah oui bon...

peut-être un début de solution

Code : Tout sélectionner

#LVM_SUBITEMHITTEST = #LVM_FIRST+57 

If OpenWindow(0, 100, 100, 300, 100, "ListIcon Example", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
		If CreateGadgetList(WindowID(0))
			ListIconGadget(0, 5, 5, 290, 90, "Name", 100, #PB_ListIcon_AlwaysShowSelection)
			AddGadgetColumn(0, 1, "Address", 250)
			AddGadgetItem(0, -1, "Harry Rannit"+Chr(10)+"12 Parliament Way, Battle Street, By the Bay")
			AddGadgetItem(0, -1, "Ginger Brokeit"+Chr(10)+"130 PureBasic Road, BigTown, CodeCity")
			Repeat
				Event = WaitWindowEvent()
				If event=#WM_LBUTTONDOWN
					Define PInfo.LVHITTESTINFO
					GetCursorPos_(rc.POINT)
					MapWindowPoints_(0, GadgetID(0),rc,1)
					PInfo\pt\x = rc\x
					PInfo\pt\y = rc\y 
					SendMessage_(GadgetID(0), #LVM_SUBITEMHITTEST, 0, PInfo) 
					Debug "("+Str(PInfo\iItem)+", "+Str(PInfo\iSubitem)+")"
				EndIf
			Until Event = #PB_Event_CloseWindow
		EndIf
EndIf
post vu sur forum anglais = http://www.purebasic.fr/english/viewtop ... ilit=egrid

Re: Création de fonctions tableau

Publié : mer. 27/avr./2011 10:18
par Patrick88
c'était ça... (post précédent) en cherchant sur code archive, je t'ai trouvé ce petit bijou, on dit merciki ?

Code : Tout sélectionner

; English forum: http://www.purebasic.fr/english/viewtopic.php?t=8860&highlight=
; Author: srod (updated for PB4.00 by blbltheworm)
; Date: 01. January 2004
; OS: Windows
; Demo: No


; Here is a piece of code which I haven't had time to complete as yet but offers
; a GRID in which selections of multiple cells / columns / rows can be made.

; It's approach is not quite as subtle as Einander's but as I say it does allow
; for click and drag type selections.
; It's unlikely that I will fully complete the code but most of the 'leg work' is done.


;PureGRID version 1.0 by Stephen Rodriguez.
;
;Nov 2003.
;********************************************


;This source file allows the programmer to utilise a small GRID control within an application.
;This file should ideally be 'XIncludeFile' at the beginning of an application.

;The programmer first needs to construct a '_PureGRID' structure and pass a pointer to this to the OpenPureGRID procedure.
;On return from this module, the '_PureGRID' structure will be modified to reflect changes made by the
;user etc. In particular,the underlying data array will reflect any changes made.


Structure _PureGRID
  PtrDataArray.l; This should contain the address of a string array used to hold the underlying data.
  ; Dim DataArray.s (NumberRows, NumberCols). PtrDataArray = DataArray().
  NumberRows.w; The number of rows in the underlying DataArray excluding row(0) which contains column headings (optional)
  NumberColumns.w; The number of columns in the underlying DataArray excluding column(0) which contains optional row headings.
  ColumnHeadings.b; 1 = Yes.  Flag to indicate whether read-only column headings are included within the DataArray
  RowHeadings.b; 1 = Yes.  Flag to indicate whether read-only row headings are included within the DataArray.
  ReadOnly.b; 1 = Read only. Flag to indicate whether the underlying data array can be written to.
EndStructure


Enumeration
#PureGRID_Window = 900
#PureGRID_ZoomWindow
#PureGRID_Menu
EndEnumeration

;Menu enumeration.
Enumeration
#MenuPureGRID_Copy
#MenuPureGRID_Cut
#MenuPureGRID_Paste
#MenuPureGRID_Clear
#MenuPureGRID_Zoom
EndEnumeration

;Gadget enumeration.
Enumeration
#PureGRID_Container=900
#PureGRID_HScroll
#PureGRID_VScroll
#PureGRID_ZoomEdit
#PureGRID_ZoomButtonOkay
#PureGRID_ZoomButtonCancel
#PureGRID_StringBase
EndEnumeration

;Font enumeration
Enumeration
#PureGRID_Font1=900
#PureGRID_Font2
EndEnumeration


Enumeration; Used for selecting rectangular regions.
#Inactive
#BeginSelect
#SizingSelect
#RectangleSelected
EndEnumeration


;Declare constants.
#PureGRID_Yes = 1 : #PureGRID_No = 0 : #PureGRID_DefaultCellWidth = 100 : #PureGRID_DefaultCellHeight = 20
#PureGRID_EnableZoomBox = #PureGRID_Yes; Change this option if you do not wish to offer the Zoom Box facility.

;Declare globals.
Global PureGRID_DisplayedRows.b, PureGRID_DisplayedColumns; No. of rows/columns to be displayed.
Global PureGRID_DefaultDisplayedRows.b, PureGRID_DefaultDisplayedColumns.b; Default no. of rows/columns to be displayed.
Global PureGRID_Left.w, PureGRID_Top.w; Used to indicate which data item occupies GRID cell (1, 1).
Global PureGRID_x.w, PureGRID_y.w; Points to the GRID cell with the focus; NOT the corresponding element within the data array.
Global PureGRID_DataRows.w, PureGRID_DataColumns.w, PureGRID_RowHeadings.b, PureGRID_ColumnHeadings.b, PureGRID_PtrDataArray, PureGRID_ReadOnly.b; These are used to record information about the underlying data array.
Global PureGRID_SelectingRectangle.b, PureGRID_Rectangle.RECT; Used when selecting a region.
Global BlackBrush.l, WhiteBrush.l; Used when highlighting selected cells.
;Declare fonts used.
LoadFont(#PureGRID_Font1, "Arial", 10, #PB_Font_Bold)
LoadFont(#PureGRID_Font2, "Arial", 10)


;Declare procedures.
Declare InitialisePureGRIDVariables()
Declare OpenPureGRID(*GRID._PureGRID, Title$)
Declare CreatePureGRIDGadgets(Title$)
Declare PaintPureGRID(flag.b)
Declare PureGRIDWriteDataFromCell(tempx.w, tempy.w)
Declare PureGRIDRowColumnIdentify(*temp.POINT)
Declare WindowCallBack(WindowID,Message,wParam,lParam)
Declare PureGRIDZoom()

;Set up some dummy data for testing purposes.
PureGRID._PureGRID
PureGRID\NumberRows = 20
PureGRID\NumberColumns = 16
PureGRID\ColumnHeadings = #PureGRID_No
PureGRID\RowHeadings = #PureGRID_No
PureGRID\ReadOnly = #PureGRID_No
Global Dim DataArray.s (20,16)

For PureGRID_LoopRow = 1 To PureGRID\NumberRows
  For PureGRID_LoopCol = 1 To PureGRID\NumberColumns
    DataArray(PureGRID_LoopRow, PureGRID_LoopCol) = "(" + Str(PureGRID_LoopRow) + ", " + Str(PureGRID_LoopCol) +  ")"
  Next PureGRID_LoopCol
Next PureGRID_LoopRow

PureGRID\PtrDataArray = DataArray()
OpenPureGRID(@PureGRID, "TESTING.")
End

;End of setting up dummy data.


;The following procedure initialises global variables etc.
Procedure InitialisePureGRIDVariables()
  ;First calculate the possible number of rows and columns which can fit on the screen.
  ;This obviously depends upon the screen resolution etc.
  PureGRID_DefaultDisplayedRows = 15
  PureGRID_DefaultDisplayedColumns = WindowWidth(#PureGRID_Window)/#PureGRID_DefaultCellWidth - 2
  PureGRID_Left = 1
  PureGRID_Top = 1
  PureGRID_x = 1
  PureGRID_y = 1
  PureGRID_Rectangle\left = -1:PureGRID_Rectangle\Top = -1:PureGRID_Rectangle\right = -1:PureGRID_Rectangle\bottom = -1
  PureGRID_SelectingRectangle = #Inactive
  ;Create brushes used in highlighting selected cells.
  BlackBrush = CreateSolidBrush_($0)
  WhiteBrush = CreateSolidBrush_($FFFFFF)
EndProcedure


Procedure CreatePureGRIDGadgets(Title$)
  Protected LoopRow, LoopColumn, OldAddress, ContainerWidth, ContainerHeight, Style
  ;The TempDataArray essentially points to the actual underlying data array.
  Global Dim TempDataArray.s(PureGRID_DataRows, PureGRID_DataColumns)
  OldAddress = TempDataArray()
  TempDataArray() = PureGRID_PtrDataArray
  ;Finished setting up TempDataArray.
  
  ;First load the underlying data array with default row and column headings if none are given.
  If PureGRID_ColumnHeadings = #PureGRID_No
    For LoopColumn = 1 To PureGRID_DataColumns
      TempDataArray(0, LoopColumn) = "Col " + Str(LoopColumn)
    Next LoopColumn
  EndIf
  If PureGRID_RowHeadings = #PureGRID_No
    For LoopRow = 1 To PureGRID_DataRows
      TempDataArray(LoopRow,0) = "Row " + Str(LoopRow)
    Next LoopRow
  EndIf
  ;Finished loading row and column headings.
  
  ;Now set up the main gadgets.
  ContainerWidth = (PureGRID_DisplayedColumns+1)*(#PureGRID_DefaultCellWidth+1)+20
  ContainerHeight = (PureGRID_DisplayedRows+1)*(#PureGRID_DefaultCellHeight+1)+20
  CreateGadgetList(WindowID(#PureGRID_Window))
  ContainerGadget(#PureGRID_Container,(WindowWidth(#PureGRID_Window) - ContainerWidth)/2,(WindowHeight(#PureGRID_Window) - ContainerHeight)/3,ContainerWidth,ContainerHeight,#PB_Container_BorderLess)
  For LoopRow = 0 To PureGRID_DisplayedRows
    For LoopColumn = 0 To PureGRID_DisplayedColumns
      If LoopRow = 0 Or LoopColumn = 0
        ButtonGadget(#PureGRID_StringBase + (LoopRow)*(PureGRID_DisplayedColumns+1) + LoopColumn,(#PureGRID_DefaultCellWidth+1)*(LoopColumn),(#PureGRID_DefaultCellHeight+1)*(LoopRow),#PureGRID_DefaultCellWidth,#PureGRID_DefaultCellHeight,"")
        SetGadgetFont(#PureGRID_StringBase + (LoopRow)*(PureGRID_DisplayedColumns+1) + LoopColumn,FontID(#PureGRID_Font1))
      Else
        Style = #PB_String_BorderLess | #ES_MULTILINE 
        If PureGRID_ReadOnly = #PureGRID_Yes
          Style = Style | #PB_String_ReadOnly
        EndIf
        StringGadget(#PureGRID_StringBase + (LoopRow)*(PureGRID_DisplayedColumns+1) + LoopColumn,(#PureGRID_DefaultCellWidth+1)*(LoopColumn),(#PureGRID_DefaultCellHeight+1)*(LoopRow),#PureGRID_DefaultCellWidth,#PureGRID_DefaultCellHeight,"", Style)
        SetGadgetFont(#PureGRID_StringBase + (LoopRow)*(PureGRID_DisplayedColumns+1) + LoopColumn,FontID(#PureGRID_Font2))
      EndIf
      SetGadgetText(#PureGRID_StringBase + (LoopRow)*(PureGRID_DisplayedColumns+1) + LoopColumn, TempDataArray(LoopRow, LoopColumn))
    Next LoopColumn
  Next LoopRow
  ;Now for the scroll bar gadgets.
  ScrollBarGadget(#PureGRID_HScroll, #PureGRID_DefaultCellWidth+1, (PureGRID_DisplayedRows+1)*(#PureGRID_DefaultCellHeight+1),(PureGRID_DisplayedColumns)*(#PureGRID_DefaultCellWidth+1), 20, 1, PureGRID_DataColumns, PureGRID_DisplayedColumns)
  ScrollBarGadget(#PureGRID_VScroll, (PureGRID_DisplayedColumns+1)*(#PureGRID_DefaultCellWidth+1),#PureGRID_DefaultCellHeight+1, 20, (PureGRID_DisplayedRows)*(#PureGRID_DefaultCellHeight+1), 1, PureGRID_DataRows, PureGRID_DisplayedRows, #PB_ScrollBar_Vertical)
  CloseGadgetList()
  SetActiveGadget(#PureGRID_StringBase+1*(PureGRID_DisplayedColumns+1) +1); Cell (1, 1)
  ;Tidy up.
  TempDataArray() = OldAddress; Restore temporary array.
  Global Dim TempDataArray.s(0,0); Free temporary array
  ;End of tidying up.
EndProcedure


;The following procedure re-paints the GRID, typically after it has been scrolled etc.
Procedure PaintPureGRID(flag.b); Flag = 1 for setting fonts only; 0 for writing data.
  Protected LoopRow, LoopColumn, OldAddress
  ;The TempDataArray essentially points to the actual underlying data array.
  Global Dim TempDataArray.s(PureGRID_DataRows, PureGRID_DataColumns)
  OldAddress = TempDataArray()
  TempDataArray() = PureGRID_PtrDataArray
  ;Finished setting up TempDataArray.
  ;Now re-paint the GRID with the correct contents taken from the underlying data array.
  For LoopRow = flag To PureGRID_DisplayedRows
    For LoopColumn = flag To PureGRID_DisplayedColumns
      If LoopRow = 0 And LoopColumn = 0; Ignore this cell.
      ElseIf LoopRow = 0
        SetGadgetText(#PureGRID_StringBase + (LoopRow)*(PureGRID_DisplayedColumns+1) + LoopColumn,TempDataArray(LoopRow, LoopColumn+PureGRID_Left-1))
      ElseIf LoopColumn = 0
        SetGadgetText(#PureGRID_StringBase + (LoopRow)*(PureGRID_DisplayedColumns+1) + LoopColumn,TempDataArray(LoopRow+PureGRID_Top-1, LoopColumn))
      Else
        If flag = 0; Write data only if required.
          SetGadgetText(#PureGRID_StringBase + (LoopRow)*(PureGRID_DisplayedColumns+1) + LoopColumn,TempDataArray(LoopRow+PureGRID_Top-1, LoopColumn+ PureGRID_Left-1))
        EndIf
        ;The following SetGadgetFont statement will cause the WindowCallBack procedure to be called which will
        ;set the background colour as appropriate.
        SetGadgetFont(#PureGRID_StringBase + (LoopRow)*(PureGRID_DisplayedColumns+1) + LoopColumn,FontID(#PureGRID_Font2))
      EndIf
    Next LoopColumn
  Next LoopRow
  ;Adjust cursor position after any possible scrolling etc.
  ;Activate relevant string gadget.
  If PureGRID_x < PureGRID_Left
    PureGRID_x = PureGRID_Left
  EndIf
  If PureGRID_x >= PureGRID_Left + PureGRID_DisplayedColumns
    PureGRID_x = PureGRID_Left + PureGRID_DisplayedColumns-1
  EndIf
  If PureGRID_y < PureGRID_Top
    PureGRID_y = PureGRID_Top
  EndIf
  If PureGRID_y >= PureGRID_Top + PureGRID_DisplayedRows
    PureGRID_y = PureGRID_Top + PureGRID_DisplayedRows - 1
  EndIf
  ;Now highlight the text within the selected string gadget.
  SetActiveGadget(#PureGRID_StringBase+(PureGRID_y-PureGRID_Top+1)*(PureGRID_DisplayedColumns+1) + PureGRID_x-PureGRID_Left+1)
  ;Tidy up.
  TempDataArray() = OldAddress; Restore temporary array.
  Global Dim TempDataArray.s(0,0); Free temporary array
  ;End of tidying up.
EndProcedure


;The following procedure performs all writing of data to the underlying array.
;This ensures that we can introduce an 'Undo' facility later.
Procedure PureGRIDWriteDataFromCell(tempx.w, tempy.w); (tempx, tempy) point to the underlying data array.
  Protected LoopRow.b, LoopColumn.b, OldAddress
  ;The TempDataArray essentially points to the actual underlying data array.
  Global Dim TempDataArray.s(PureGRID_DataRows, PureGRID_DataColumns)
  OldAddress = TempDataArray()
  TempDataArray() = PureGRID_PtrDataArray
  ;Finished setting up TempDataArray.
  ;Now copy data from the GRID ONLY if it HAS NOT been altered at all. This will allow for an UNDO action later.
  If TempDataArray(tempy, tempx) <> GetGadgetText(#PureGRID_StringBase+(tempy-PureGRID_Top+1)*(PureGRID_DisplayedColumns+1) + tempx-PureGRID_Left+1)
    
    ;INSERT CODE FOR DEALING WITH AN UNDO FACILITY.
    
    TempDataArray(tempy, tempx) = GetGadgetText(#PureGRID_StringBase+(tempy-PureGRID_Top+1)*(PureGRID_DisplayedColumns+1) + tempx-PureGRID_Left+1)
  EndIf
  ;Tidy up.
  TempDataArray() = OldAddress; Restore temporary array.
  Global Dim TempDataArray.s(0,0); Free temporary array
  ;End of tidying up.
EndProcedure


;The following procedure involves calling the Windows API to convert the cursor screen coordinates
;into coordinates relative to the top left of the container gadget.
;This could be done using PB's WindowMouseX and WindowMouseY functions but that then leaves the task
;of determining where in the gadget the cursor is pointing to the programmer.
;The coordinates are then converted into the (row,column) position of the underlying data array which has the focus.
;(NOT the respective string gadget.) This data is then placed into the PureGRID_Rectangle structure as appropriate.
Procedure PureGRIDRowColumnIdentify(*temp.POINT)
  Protected Column.w, Row.w, temporary.f
  GetCursorPos_(*temp)
  MapWindowPoints_(0,GadgetID(#PureGRID_Container),*temp,1)
  ;First identify the (row, column) GRID coordinates of the gadget with the focus.
  Column = Round(*temp\x /(#PureGRID_DefaultCellWidth+1),0); Ensures calculation is rounded down.
  Row = Round(*temp\y /(#PureGRID_DefaultCellHeight+1),0);Avoids problems with -0.6 being rounded to 0 etc.
  ;Now convert to the coordinates of the respective cell in the underlying data array.
  *temp\x = Column+PureGRID_Left-1
  *temp\y = Row+PureGRID_Top-1
EndProcedure


;The following procedure deals with the zoom facility.
Procedure PureGRIDZoom()
  OpenWindow(#PureGRID_ZoomWindow,175,0,639,243,"ZOOM BOX",#PB_Window_SystemMenu|#PB_Window_TitleBar|#PB_Window_ScreenCentered, WindowID(#PureGRID_Window))
  CreateGadgetList(WindowID(#PureGRID_ZoomWindow))
  EditorGadget(#PureGRID_ZoomEdit,49,37,450,150,#PB_String_ReadOnly)
  ;Send an API message to set read only if appropriate.
  SendMessage_(GadgetID(#PureGRID_ZoomEdit),#EM_SETREADONLY, PureGRID_ReadOnly, 0)
  ButtonGadget(#PureGRID_ZoomButtonOkay,520,116,85,30,"OKAY")
  ButtonGadget(#PureGRID_ZoomButtonCancel,520,156,85,30,"CANCEL")
  SetGadgetText(#PureGRID_ZoomEdit,GetGadgetText(#PureGRID_StringBase+(PureGRID_y-PureGRID_Top+1)*(PureGRID_DisplayedColumns+1) + PureGRID_x-PureGRID_Left+1))
  SetActiveGadget(#PureGRID_ZoomEdit)
  Repeat
    EventID=WaitWindowEvent()
  Until EventID=#PB_Event_CloseWindow Or (EventID = #PB_Event_Gadget And EventGadget() = #PureGRID_ZoomButtonOkay) Or (EventID = #PB_Event_Gadget And EventGadget() = #PureGRID_ZoomButtonCancel)
  ;Now write data back to the GRID only if the proceed button was pushed.
  If EventID = #PB_Event_Gadget And EventGadget() = #PureGRID_ZoomButtonOkay
    SetGadgetText(#PureGRID_StringBase+(PureGRID_y-PureGRID_Top+1)*(PureGRID_DisplayedColumns+1) + PureGRID_x-PureGRID_Left+1, GetGadgetText(#PureGRID_ZoomEdit))
  EndIf
  CloseWindow(#PureGRID_ZoomWindow)
  SetActiveGadget(#PureGRID_StringBase+(PureGRID_y-PureGRID_Top+1)*(PureGRID_DisplayedColumns+1) + PureGRID_x-PureGRID_Left+1)
EndProcedure


;The main procedure.
Procedure OpenPureGRID(*GRID._PureGRID, Title$)
  Protected temp.POINT, x.w, y.w, flag.b
  If Title$ <> ""
    Title$ = Title$ + "     "
  EndIf
  Title$ = Title$ + "PRESS F2 TO OPEN A 'ZOOM' BOX."
  OpenWindow(#PureGRID_Window,0,0,400,400,Title$,  #PB_Window_Invisible | #PB_Window_MinimizeGadget | #PB_Window_MaximizeGadget)
  ShowWindow_(WindowID(#PureGRID_Window), #SW_MAXIMIZE)
  ;  SetClassLong_(WindowID(), #GCL_STYLE, GetClassLong_(WindowID(), #GCL_STYLE)|#CS_DBLCLKS); This allows the trapping of double click events.
  
  ;Initialise global variables.
  InitialisePureGRIDVariables()
  
  ;Load data array and associated information.
  PureGRID_PtrDataArray = *GRID\PtrDataArray; This gives direct access to the underlying DataArray.
  PureGRID_DataRows = *GRID\NumberRows
  PureGRID_DataColumns = *GRID\NumberColumns
  PureGRID_RowHeadings = *GRID\RowHeadings
  PureGRID_ColumnHeadings = *GRID\ColumnHeadings
  PureGRID_ReadOnly = *GRID\ReadOnly
  ;The PureGRID_DisplayedRows / Columns variables denote the number of visible rows / columns.
  ;These are either default values (depending on window size) or the actual dimensions of the underlying
  ;data array; whichever is the smaller.
  PureGRID_DisplayedRows = PureGRID_DefaultDisplayedRows
  If PureGRID_DataRows < PureGRID_DefaultDisplayedRows : PureGRID_DisplayedRows = PureGRID_DataRows : EndIf
  PureGRID_DisplayedColumns = PureGRID_DefaultDisplayedColumns
  If PureGRID_DataColumns < PureGRID_DefaultDisplayedColumns : PureGRID_DisplayedColumns = PureGRID_DataColumns : EndIf
  ;End of loading data.
  
  ;Create menu.
  CreateMenu(#PureGRID_Menu, WindowID(#PureGRID_Window))
  MenuTitle("Edit")
  MenuItem(#MenuPureGRID_Copy, "Copy" + Chr(9) + "(Ctrl+c)")
  MenuItem(#MenuPureGRID_Cut, "Cut"+Chr(9)+"(Ctrl+x)")
  MenuItem(#MenuPureGRID_Paste, "Paste"+Chr(9)+"(Ctrl+v)")
  MenuItem(#MenuPureGRID_Clear, "Clear")
  MenuItem(#MenuPureGRID_Zoom, "Zoom box"+Chr(9)+"(F2)")
  ;Create menu shortcuts.
  AddKeyboardShortcut(#PureGRID_Window, #PB_Shortcut_F2, #MenuPureGRID_Zoom)
  
  
  CreatePureGRIDGadgets(Title$)
  SetWindowCallback(@WindowCallBack())
  
  ;Main event loop.
  Repeat
    ;Check to see if the user has pressed the tab key.
    ;In which case we must ensure correct movement through the GRID.
    If GetAsyncKeyState_(#VK_TAB) & 1 = 1;  Bit 0 is set if the tab key was pressed since the last check.
      flag = 2; Used to determine how the GRID will be painted. 2 means NO PAINT required.
      ;Write data back to the data array if it has changed.
      PureGRIDWriteDataFromCell(PureGRID_x, PureGRID_y)
      
      If PureGRID_x <  PureGRID_DataColumns; Scroll right.
        PureGRID_x = PureGRID_x + 1
        ;Check if we've moved to far right.
        If PureGRID_x >= PureGRID_Left + PureGRID_DisplayedColumns
          SetGadgetState(#PureGRID_HScroll, GetGadgetState(#PureGRID_HScroll)+1)
          PureGRID_Left = GetGadgetState(#PureGRID_HScroll)
          flag = 0; Complete paint required, including text.
        EndIf
      ElseIf PureGRID_y < PureGRID_DataRows;  Need to move the focus down a row.
        PureGRID_x = 1
        SetGadgetState(#PureGRID_HScroll, 1)
        If PureGRID_Left > 1
          PureGRID_Left = 1
          flag = 0
        EndIf
        PureGRID_y = PureGRID_y + 1
        If PureGRID_y >= PureGRID_Top + PureGRID_DisplayedRows
          SetGadgetState(#PureGRID_VScroll, GetGadgetState(#PureGRID_VScroll)+1)
          PureGRID_Top = GetGadgetState(#PureGRID_VScroll)
          flag = 0
        EndIf
      EndIf
      ;Clear any current selection.
      PureGRID_Rectangle\right = -1 : PureGRID_Rectangle\bottom = -1
      If PureGRID_SelectingRectangle = #RectangleSelected
        If flag > 0 : flag = 1 : EndIf; Only the font properties etc. need painting.
        PureGRID_SelectingRectangle = #Inactive
      EndIf
      If flag < 2
        PaintPureGRID(flag)
      EndIf
      ;Now highlight the relevant gadget.
      SetActiveGadget(#PureGRID_StringBase+(PureGRID_y-PureGRID_Top+1)*(PureGRID_DisplayedColumns+1) + PureGRID_x-PureGRID_Left+1)
      SendMessage_(GadgetID(#PureGRID_StringBase+(PureGRID_y-PureGRID_Top+1)*(PureGRID_DisplayedColumns+1) + PureGRID_x-PureGRID_Left+1),#EM_SETSEL, 0, -1)
    EndIf
    
    
    EventID=WaitWindowEvent()
    
    If EventType() = #PB_EventType_Change; Indicates that the contents of a string gadget have changed.
      ;Clear any current selection.
      PureGRID_Rectangle\right = -1 : PureGRID_Rectangle\bottom = -1
      If PureGRID_SelectingRectangle <> #Inactive
        PaintPureGRID(1)
        PureGRID_SelectingRectangle = #Inactive;
      EndIf
    EndIf
    Select EventID
    Case #WM_LBUTTONDOWN
      ;Here the user is probably about to select a region to copy / cut etc.
      ;First write data back to the data array if it has changed.
      PureGRIDWriteDataFromCell(PureGRID_x, PureGRID_y)
      ;We call a function to get the mouse (x, y) co-ordinates relative to the top-left of the container gadget
      ;and the coordinates are then converted into the (row,column) position of the underlying data array which has the focus.
      PureGRIDRowColumnIdentify(@temp); The point structure will hold the retrieved data.
      ;Check whether the 'data point' is within the visible GRID.
      If temp\x >= PureGRID_Left And temp\x < PureGRID_Left + PureGRID_DisplayedColumns And temp\y >= PureGRID_Top And temp\y < PureGRID_Top + PureGRID_DisplayedRows
        ;Clear any current selection.
        PureGRID_Rectangle\right = -1 : PureGRID_Rectangle\bottom = -1
        ;Set the initial top-left corner of the PureGRID_Rectangle structure to the current point.
        x = temp\x
        y = temp\y
        ;And the current cursor position.
        PureGRID_x = temp\x
        PureGRID_y = temp\y
        If PureGRID_SelectingRectangle = #RectangleSelected Or PureGRID_SelectingRectangle = #SizingSelect
          PaintPureGRID(1); This will remove the current selection.
        EndIf
        ;Flag that the selection process has begun.
        PureGRID_SelectingRectangle = #BeginSelect
      ElseIf temp\x = PureGRID_Left-1 And temp\y = PureGRID_Top -1; Indicates that the whole data set has been selected.
        PureGRID_Rectangle\left = 1
        PureGRID_Rectangle\Top = 1
        PureGRID_Rectangle\right = PureGRID_DataColumns
        PureGRID_Rectangle\bottom = PureGRID_DataRows
        PaintPureGRID(1); This will highlight the current selection.
        PureGRID_SelectingRectangle = #RectangleSelected
      ElseIf temp\x = PureGRID_Left-1 And temp\y >= PureGRID_Top And temp\y < PureGRID_Top + PureGRID_DisplayedRows; Indicates that a row has been selected.
        x = 0 : y = temp\y; The 0 indicates that a whole row has been selected.
        ;Highlight the selected row.
        PureGRID_Rectangle\left = 1
        PureGRID_Rectangle\Top = temp\y
        PureGRID_Rectangle\right = PureGRID_DataColumns
        PureGRID_Rectangle\bottom = temp\y
        PaintPureGRID(1); This will highlight the current selection.
        PureGRID_SelectingRectangle = #SizingSelect
      ElseIf temp\y = PureGRID_Top-1 And temp\x >= PureGRID_Left And temp\x < PureGRID_Left + PureGRID_DisplayedColumns; Indicates that a column has been selected.
        y = 0 : x = temp\x; The 0 indicates that a whole column has been selected.
        ;Highlight the selected column.
        PureGRID_Rectangle\left = temp\x
        PureGRID_Rectangle\Top = 1
        PureGRID_Rectangle\right = temp\x
        PureGRID_Rectangle\bottom = PureGRID_DataRows
        PaintPureGRID(1); This will highlight the current selection.
        PureGRID_SelectingRectangle = #SizingSelect
      EndIf
      
    Case #WM_LBUTTONUP
      Select PureGRID_SelectingRectangle
      Case #BeginSelect
        PureGRID_SelectingRectangle = #Inactive
      Case #SizingSelect
        PureGRID_SelectingRectangle = #RectangleSelected
      EndSelect
      
    Case #WM_MOUSEMOVE
      ;If the user is in the middle of selecting a rectangle then we need to adjust the selection rectangle etc.
      If PureGRID_SelectingRectangle = #BeginSelect Or PureGRID_SelectingRectangle = #SizingSelect
        flag = 1; Indicate that repainting requires only change of background colour etc.
        ;We call a function to get the mouse (x, y) co-ordinates relative to the top-left of the container gadget
        ;and the coordinates are then converted into the (row,column) position of the underlying data array which has the focus.
        PureGRIDRowColumnIdentify(@temp); The point structure will hold the retrieved data.
        
        ;CODE FOR SCROLLING SELECTION.
        ;Check if the cursor is too far right.
        If (temp\x >= PureGRID_Left + PureGRID_DisplayedColumns)
          SetGadgetState(#PureGRID_HScroll, GetGadgetState(#PureGRID_HScroll)+1)
          PureGRID_Left = GetGadgetState(#PureGRID_HScroll)
          flag = 0
        EndIf
        ;Check if the cursor is too far left. Must also check that row selection is not engaged.
        If (temp\x < PureGRID_Left) And x > 0
          SetGadgetState(#PureGRID_HScroll, GetGadgetState(#PureGRID_HScroll)-1)
          PureGRID_Left = GetGadgetState(#PureGRID_HScroll)
          flag = 0
        EndIf
        ;Check if the cursor is too far down.
        If (temp\y >= PureGRID_Top + PureGRID_DisplayedRows)
          SetGadgetState(#PureGRID_VScroll, GetGadgetState(#PureGRID_VScroll)+1)
          PureGRID_Top = GetGadgetState(#PureGRID_VScroll)
          flag = 0
        EndIf
        ;Check if the cursor is too far up. Must also check that column selection is not engaged.
        If (temp\y < PureGRID_Top) And y > 0
          SetGadgetState(#PureGRID_VScroll, GetGadgetState(#PureGRID_VScroll)-1)
          PureGRID_Top = GetGadgetState(#PureGRID_VScroll)
          flag = 0
        EndIf
        
        If x = 0; Row selection.
          If temp\y < y
            PureGRID_Rectangle\bottom = y
            PureGRID_Rectangle\Top = temp\y
          Else
            PureGRID_Rectangle\Top = y
            PureGRID_Rectangle\bottom = temp\y
          EndIf
          
        ElseIf y = 0; Column selection.
          If temp\x < x
            PureGRID_Rectangle\right = x
            PureGRID_Rectangle\left = temp\x
          Else
            PureGRID_Rectangle\left = x
            PureGRID_Rectangle\right = temp\x
          EndIf
          
          ;Adjust coordinates so that (PureGRID_Rectangle\left, PureGRID_Rectangle\top) points to the top left of the selection etc.
        Else
          PureGRID_Rectangle\right = temp\x
          PureGRID_Rectangle\bottom = temp\y
          If x > PureGRID_Rectangle\right
            PureGRID_Rectangle\left = PureGRID_Rectangle\right
            PureGRID_Rectangle\right = x
          Else
            PureGRID_Rectangle\left = x
          EndIf
          If y > PureGRID_Rectangle\bottom
            PureGRID_Rectangle\Top = PureGRID_Rectangle\bottom
            PureGRID_Rectangle\bottom = y
          Else
            PureGRID_Rectangle\Top = y
          EndIf
        EndIf
        PaintPureGRID(flag); This will highlight the current selection.
        PureGRID_SelectingRectangle = #SizingSelect
      EndIf
      
    Case #PB_Event_Menu
      ;Write data back to the data array if it has changed.
      PureGRIDWriteDataFromCell(PureGRID_x, PureGRID_y)
      Select EventMenu()
      Case #MenuPureGRID_Zoom
        ;Clear any current selection.
        PureGRID_Rectangle\right = -1 : PureGRID_Rectangle\bottom = -1
        If PureGRID_SelectingRectangle <> #Inactive
          PaintPureGRID(1)
          PureGRID_SelectingRectangle = #Inactive;
        EndIf
        ;Call Zoom procedure.
        PureGRIDZoom()
        ;Write data back to the data array if it has changed.
        PureGRIDWriteDataFromCell(PureGRID_x, PureGRID_y)
      EndSelect
      
      
    Case #PB_Event_Gadget
      Select EventGadget()
      Case #PureGRID_HScroll; Indicates that the horziontal scroll bar has been adjusted.
        If PureGRID_Left <> GetGadgetState(#PureGRID_HScroll); Save some processing time by making this check.
          ;Write data back to the data array if it has changed.
          PureGRIDWriteDataFromCell(PureGRID_x, PureGRID_y)
          PureGRID_Left = GetGadgetState(#PureGRID_HScroll)
          PaintPureGRID(0)
        EndIf
      Case #PureGRID_VScroll; Indicates that the vertical scroll bar has been adjusted.
        If PureGRID_Top <> GetGadgetState(#PureGRID_VScroll); Save some processing time by making this check.
          ;Write data back to the data array if it has changed.
          PureGRIDWriteDataFromCell(PureGRID_x, PureGRID_y)
          PureGRID_Top = GetGadgetState(#PureGRID_VScroll)
          PaintPureGRID(0)
        EndIf
      EndSelect
      Default
    EndSelect
  Until EventID=#PB_Event_CloseWindow
  ;Write data back to the data array if it has changed.
  PureGRIDWriteDataFromCell(PureGRID_x, PureGRID_y)
  ;Delete the rosources given over to the two brushes.
  DeleteObject_(BlackBrush)
  DeleteObject_(WhiteBrush)
EndProcedure


;The following callback procedure intercepts the drawing of each string gadget.
;This makes it possible to highlight any selected gadgets.
Procedure WindowCallBack(WindowID,Message,wParam,lParam)
  ReturnValue=#PB_ProcessPureBasicEvents
  If Message=#WM_CTLCOLOREDIT; This indicates that one of the string gadgets is about to be drawn.
    ;We first need to identify which string gadget is being drawn.
    For LoopRow = 1 To PureGRID_DisplayedRows
      For LoopColumn = 1 To PureGRID_DisplayedColumns
        If lParam = GadgetID(#PureGRID_StringBase + (LoopRow)*(PureGRID_DisplayedColumns+1) + LoopColumn)
          Break 2; Break out of the 2 loops.
        EndIf
      Next LoopColumn
    Next LoopRow
    ;(LoopRow, LoopColumn) identifies the string gadget being drawn.
    ;Now check if the string gadget is within a selected region.
    SetBkMode_(wParam,#OPAQUE)
    If (PureGRID_Rectangle\right <>-1) And ((LoopColumn + PureGRID_Left-1) >= PureGRID_Rectangle\left) And ((LoopColumn + PureGRID_Left-1) <= PureGRID_Rectangle\right) And ((LoopRow + PureGRID_Top-1) >= PureGRID_Rectangle\Top) And ((LoopRow + PureGRID_Top-1) <= PureGRID_Rectangle\bottom)
      SetTextColor_(wParam,$FFFFFF)
      SetBkColor_(wParam,$0000)
      ReturnValue=BlackBrush
    Else
      SetBkColor_(wParam,$FFFFFF)
      ReturnValue=WhiteBrush
    EndIf
  EndIf
  ProcedureReturn  ReturnValue
EndProcedure


; IDE Options = PureBasic v4.00 (Windows - x86)
; Folding = --
; EnableXP
; DisableDebugger

Re: Création de fonctions tableau

Publié : mer. 27/avr./2011 10:25
par Patrick88
et zou un autre...

Code : Tout sélectionner

; English forum: http://www.purebasic.fr/english/viewtopic.php?t=12957
; Author: Manolo (updated for PB 4.00 by Andre)
; Date: 29. October 2004
; OS: Windows
; Demo: No


; Original was:
; -------------
; English forum: http://purebasic.myforums.net/viewtopic.php?t=8860&highlight=
; Author: einander
; Date: 26. December 2003

; GRID with input text
; December 26 -2003- PB 3.81
; by Einander
;
; Useful additions are:
; ---------------------
; -Implementation of direct input in the cell
; -Implementation of beatiful titles with degree-colors from Num3
; -and another small changes
; -by Manolo
; -October 28, 2004 - PB 3.92

DataSection
  Dia_Semana:
  Data.s "Lun","Mar","Mie","Jue","Vie","Sab","Dom"
  Mes:
  Data.s "ENERO","FEBRERO","MARZO","ABRIL","MAYO","JUNIO","JULIO","AGOSTO","SEPTIEMBRE","OCTUBRE","NOVIEMBRE","DICIEMBRE"
EndDataSection
Global Dim Dia.s(7)
Global Dim OrgDia.s(7)
Global Dim Mes.s(12)
Restore Dia_Semana
For i=1 To 7:Read.s Dia(i):Next
Restore Mes
For i=1 To 12:Read.s Mes(i):Next

For i=1 To 7
  date+1
  Result = DayOfWeek(AddDate(Date(), #PB_Date_Day, date))
  Mes = Month(AddDate(Date(), #PB_Date_Day, date))
  Dia=Day(AddDate(Date(), #PB_Date_Day, date))
  If Result=0 :OrgDia(i)=Dia(7)+" "+Str(Dia): Else : OrgDia(i)=Dia(result)+" "+Str(Dia): EndIf
Next




;Read Dia(i)
;Next
Enumeration
  #Ret
  #Txt
  #Input
  #SepaHori
  #SepaVert
EndEnumeration

#LightGray =$AA1216;$BDBDBD
#SAND= $BBFFFF



Global Dim Selected.l(1): Global Dim textcell$(0) : Global Dim xcell.W(0) : Global Dim ycell.W(0)
Global Mx, My, Mk,S$, gad$
Global GRID, Colum, Rows, _X, _Y, WCell, HCell, XGRID, YGRID, NColumns, NRows, NCells, WGRID, HGRID, SmallFont
S$="  "

Procedure separator(id,x,y,width,height,text.s,fontid,color1,color2,Columnas,Filas)


  If CreateImage(id,width*(Columnas),height*(Filas))

    i = width
    sRed.f   = Red(color1)   : r.f = (Red  (color1) - Red  (color2))/i
    sGreen.f = Green(color1) : g.f = (Green(color1) - Green(color2))/i
    sBlue.f  = Blue(color1)  : b.f = (Blue (color1) - Blue (color2))/i

    StartDrawing(ImageOutput(id))
    Pos=0
    If id=#SepaHori
      For k=1 To Columnas
        ;----------------
        For a = 0 To i-1
          xx.f = sRed   - a*r
          yy.f = sGreen - a*g
          zz.f = sBlue  - a*b

          Line(a+Pos,0,0,height,RGB(xx,yy,zz))
        Next a
        ;----------------
        DrawingMode(1)
        FrontColor(RGB(255,156,41))
        ; FrontColor($FF,$FF,$FF)
        If fontid<>0
          DrawingFont(fontid)
        EndIf
        ;----------
        DrawText(Pos+5,2,OrgDia(k))
        Pos+width
      Next k
      StopDrawing()
    EndIf

    If id=#SepaVert
      Pos-height

      For k=-1 To Filas-1

        ;----------------
        For a = 0 To i-1

          xx.f = sRed   - a*r
          yy.f = sGreen - a*g
          zz.f = sBlue  - a*b

          Line(a,Pos,0,height,RGB(xx,yy,zz))
        Next a
        ;----------------
        DrawingMode(1)
        FrontColor(RGB(255,156,41))
        ; FrontColor($FF,$FF,$FF)
        If fontid<>0
          DrawingFont(fontid)
        EndIf
        ;----------

        If k=0
          FrontColor(RGB(255,100,200))
          Texto$="Octubre"
          DrawText(5,Pos,Texto$)
        Else
          FrontColor(RGB(255,156,41))
          Texto$="Hora"+Str(k)
          DrawText(5,Pos,Texto$)
        EndIf
        Pos+height

      Next k
      StopDrawing()
    EndIf



  EndIf

  ImageGadget(id,x,y,width,Header,ImageID(id))


EndProcedure

Procedure inmous(x, y, x1, y1)
  ProcedureReturn mx >= x And my >= y And mx <= x1 And my <= y1
EndProcedure

Procedure CleanCell(COLU, ROW)
  Global x, y ;implantada
  x = XGRID + 1 + (COLU - 1) * WCell+1
  y = YGRID + 1 + (ROW - 1) * HCell+1
  Box(X, Y-1, WCell-2, HCell-1, #SAND)
  SEL = (ROW - 1 ) * NColumns + COLU
  DrawingFont(SmallFont)
  FrontColor(RGB(0, 0, 0))
  gad$=textcell$(SEL - 1)
  minu=Len(gad$)
  While TextWidth(gad$)>(Wcell-(TextWidth("W")))
    minu-2
    gad$=Mid(textcell$(sel-1),1,minu)
  Wend
  If TextWidth(gad$)<>0
    Posicion=(WCell-TextWidth(gad$))/2
  Else
    Posicion=2
  EndIf
  ;Debug posicion
  ;Debug WCell
  ;Debug TextWidth(gad$)
  DrawText(x+Posicion,y,gad$);+"..") ;DrawText(textcell$(i))
  ; Locate(x , y) :DrawText(textcell$(SEL - 1)) ;DrawText(textcell$(SEL - 1))
  Selected(0) = 0
EndProcedure

Procedure DrawCell(Ev)
  If inmous(xGRID + 1, yGRID + 1, xGRID + wGRID - 2, yGRID + hGRID - 2)
    COLU = (MX - XGRID) / WCell + 1 : ROW = (MY - YGRID) / HCell + 1
    SEL = (ROW - 1 ) * NColumns + COLU
    If Ev = #WM_LBUTTONDOWN : ProcedureReturn SEL : EndIf
    If Selected(0) <> COLU Or Selected(1) <> ROW
      If Selected(0) : CleanCell(SELECTED(0), Selected(1)) : EndIf
      x = XGRID + (COLU - 1) * WCell + 1 : y = YGRID + ((ROW - 1) * HCell) + 1



      Box(x+1, y, WCell-2 , HCell-1 , #Green)
      DrawingMode(1)
      FrontColor(RGB(0, 0, 0))
      DrawingFont(SmallFont)
      gad$=textcell$(sel-1)
      minu=Len(gad$)
      While TextWidth(gad$)>(Wcell);-(TextLength("W")))
        minu-2
        gad$=Mid(textcell$(sel-1),1,minu)
      Wend
      If TextWidth(gad$)<>0
        Posicion=(WCell-TextWidth(gad$))/2
      Else
        Posicion=1
      EndIf

      DrawText(x+Posicion, y+1, textcell$(sel-1));+"..")
      ; Locate(x + 1, y+1) : DrawText(textcell$(SEL - 1))
      DrawingMode(1)
      Selected(0) = COLU : Selected(1) = ROW
    EndIf
  ElseIf selected(0)
    CleanCell(Selected(0), Selected(1))
    ProcedureReturn 0
  EndIf
EndProcedure

Procedure DrawGRID()
  GRID = CreateImage(1, wGRID, hGRID )
  StartDrawing(ImageOutput(1))
  DrawingMode(1)
  Box(0, 0, wGRID, hGRID, #SAND)
  Pos = HCell * NRows
  x1 = 0 : y1 = 0
  For i = 0 To NColumns
    LineXY(x1, 0, x1, Pos, #LightGray)
    x1 + WCell
  Next i
  Pos = WCell * NColumns
  For i = 0 To NRows
    LineXY(0, y1, Pos, y1)
    y1 + HCell
  Next i
  FrontColor(RGB(0, 0, 0))
  DrawingFont(SmallFont)
  For i = 0 To Ncells
    gad$=textcell$(i)
    minu=Len(gad$)
    While TextWidth(gad$)>(Wcell-(TextWidth("W")))
      minu-2
      gad$=Mid(textcell$(i),1,minu)
    Wend
    If TextWidth(gad$)<>0
      Posicion=(WCell-TextWidth(gad$))/2
    Else
      Posicion=2
    EndIf

    DrawText(xcell(i) + Posicion, ycell(i)+2, gad$);+"..") ;DrawText(textcell$(i))
  Next
  StopDrawing()
EndProcedure

;_X = GetSystemMetrics_(#SM_CXSCREEN) - 8 : _Y = GetSystemMetrics_(#SM_CYSCREEN) - 68
;hWnd = OpenWindow(0, 0, 0, _X, _Y, #WS_OVERLAPPEDWINDOW, "GRID")
hWnd =OpenWindow(0,0,0,600,400,"Nice bars",#PB_Window_TitleBar|#PB_Window_ScreenCentered|#PB_Window_SystemMenu)
AddKeyboardShortcut(0, #PB_Shortcut_Return, #Ret)
AddKeyboardShortcut(0, #PB_Shortcut_Escape, #ESC)
XGRID = 90 : YGRID = 100 ; GRID position
NColumns = 7 : NRows = 7 ; number of rows & columns
WCell = 72 : HCell = 22 ; cell sizes
SmallFont = LoadFont(0, "Tahoma ", hcell/2)

NCells = NColumns * NRows
WGRID = WCell * NColumns + 1 : HGRID = HCell * NRows + 1
Dim TextCell$(Ncells)
Dim XCell.w(Ncells)
Dim YCell.w(Ncells)

For i = 0 To ncells
  If i > 0 And i % ncolumns = 0 : x = 0 : y + hcell : EndIf
  ;TextCell$(i) ="";"Manolo" ;Str(i + 1)
  Xcell(i) = x : ycell(i) = y
  x + wcell
Next

CreateGadgetList(hWnd)
TextGadget(#Txt, _x / 2, yGRID + hGRID + 10, 100, 40, "", #PB_Text_Center | #PB_Text_Border )
StringGadget(#Input, 0, 0, 0, 0, "",#PB_String_BorderLess )
XRGRID=XGRID
YRGRID=YGRID
Filas=1
Columnas=NColumns

separator(#SepaHori,XRGRID,YGRID-HCell,WCell,HCell,"Nombre",fontid,RGB($40,$40,$40),RGB($CC,$CC,$CC), Columnas, Filas)
Columnas=1
Filas=NRows

separator(#SepaVert,XGRID-WCell+1,YRGRID-HCell,WCell,HCell,"Nombre",fontid,RGB($40,$40,$40),RGB($CC,$CC,$CC), Columnas, Filas+1)

DrawGRID()



Repeat
  MX = WindowMouseX(0) ;- GetSystemMetrics_(#SM_CYSIZEFRAME)
  MY = WindowMouseY(0) ;- GetSystemMetrics_(#SM_CYCAPTION) - GetSystemMetrics_(#SM_CYSIZEFRAME)
  If #WM_LBUTTONDOWN : mk = 1 : Else : mk = 0 : EndIf
  Ev = WindowEvent()
  StartDrawing(WindowOutput(0))
  SEL = DrawCell(Ev)
  StopDrawing()
  If SEL
    If mk
      HideGadget(#input, 0)
      ;ResizeGadget(#Input, mx, my, 200, 20)

      ResizeGadget(#Input, x, y, WCell-1,HCell-1);modificada
      SetGadgetFont(#Input,LoadFont(#Input,"Tahoma ",hcell/2,0));implantada
      SetGadgetText(#Input,textcell$(sel - 1));Implantada

      Repeat
        SetActiveGadget(#Input)
        ev = WaitWindowEvent()
        t$ = GetGadgetText(#Input)
        If GetAsyncKeyState_(#VK_ESCAPE)=-32767
          t$=textcell$(sel-1)
          SetGadgetText(#Input,textcell$(sel-1))

          Break
        EndIf
        ; Debug TextLength(t$)
        ;If TextLength(t$+"W")>wcell :Break:EndIf   ; limit for text too long
      Until ev = #PB_Event_Menu And EventMenu() = #Ret
      textcell$(sel-1)=t$
      ;If Len(t$): textcell$(sel - 1) = t$ : EndIf
      ;StopDrawing()
      drawGRID()
      ;StartDrawing(WindowOutput(0))
      SetGadgetText(#input, "")
      ResizeGadget(#input, 0, 0, 0, 0)
    EndIf
    SetGadgetText(#Txt, "Selected " + Str(SEL)+s$+textcell$(sel-1))
    selected(0) = 0
  EndIf
  If Ev = #WM_PAINT
    StartDrawing(WindowOutput(0))
    DrawImage(GRID, xGRID, yGRID)
    StopDrawing()
  EndIf
Until Ev = #PB_Event_CloseWindow
End

; IDE Options = PureBasic v4.02 (Windows - x86)
; Folding = -

Re: Création de fonctions tableau

Publié : mer. 27/avr./2011 10:27
par Patrick88
2 codes précédents trouvés sur : http://www.purearea.net/pb/english/index.htm -> user-libs -> faire une recherche (en haut à droite) avec le mot grid.

pat

Re: Création de fonctions tableau

Publié : ven. 29/avr./2011 14:36
par dayvid
Ouais super :P , merci Pat :P :D