Just hoping someone can explain why my program is defaulting to the Move_Piece procedure for the Piece Type, and not the Move_Piece procedure for the Pond type when I attempt to move a pond. When I pass a variable of Pond type to the Move_Piece procedure, "Using basic Move_Piece" gets printed instead of "1". Why is this?
I am using Ada 2005, in case that wasnt obvious by the overriding keyword. I hope I have not provided too little of information. Thanks!
chess_types.ads:
package Chess_Types is
type Color is (Black, White);
type Piece is tagged
record
Name : String (1 .. 3) := " ";
Alive : Boolean := False;
Team : Color;
Coordinate : Integer;
end record;
procedure Move_Piece(P: in out Piece);
-- Board Types
type Board_Row is array (Positive range 1 .. 8) of Piece;
type Board_Type is array (Positive range 1 .. 8) of Board_Row;
end Chess_Types;
chess_types.adb:
with Ada.Text_IO;
use Ada.Text_IO;
package body Chess_Types is
procedure Move_Piece(P: in out Piece) is
begin
Put_Line("Using basic Move_Piece");
end Move_Piece;
end Chess_types;
chess_types-piece_types.ads:
package Chess_Types.Piece_Types is
type Pond is new Piece with
record
First_Move : Boolean := True;
end record;
overriding
procedure Move_Piece(Po: in out Pond);
type Rook is new Piece with null record;
overriding
procedure Move_Piece(Ro: in out Rook);
type Knight is new Piece with null record;
overriding
procedure Move_Piece(Kn: in out Knight);
type Bishop is new Piece with null record;
overriding
procedure Move_Piece(Bi: in out Bishop);
type Queen is new Piece with null record;
overriding
procedure Move_Piece(Qu: in out Queen);
type King is new Piece with null record;
overriding
procedure Move_Piece(Ki: in out King);
end Chess_Types.Piece_Types;
chess_types-piece_types.adb:
with Ada.Text_IO;
use Ada.Text_IO;
package body Chess_Types.Piece_Types is
-- Possible_Moves : array (Integer range 1 .. 100) of Integer range 11 .. 88;
procedure Move_Piece(Po: in out Pond) is
begin
Put_Line("1");
end Move_Piece;
procedure Move_Piece(Ro: in out Rook) is
begin
Put_Line("2");
end Move_Piece;
procedure Move_Piece(Kn: in out Knight) is
begin
Put_Line("3");
end Move_Piece;
procedure Move_Piece(Bi: in out Bishop) is
begin
Put_Line("4");
end Move_Piece;
procedure Move_Piece(Qu: in out Queen) is
begin
Put_Line("5");
end Move_Piece;
procedure Move_Piece(Ki: in out King) is
begin
Put_Line("6");
end Move_Piece;
end Chess_types.Piece_Types;
chess.adb:
with Ada.Text_IO;
with Print_Things;
with Adjust_Board;
with Chess_Types;
with Chess_Types.Piece_Types;
use Ada.Text_IO;
use Print_Things;
use Adjust_Board;
use Chess_Types;
use Chess_Types.Piece_Types;
procedure Chess is
Board : Board_Type;
Move : String (1 .. 5);
Move_From : Integer range 11 .. 88;
Move_To : Integer range 11 .. 88;
begin
-- Initialize and Print default board
Initialize_Board(Board);
Print_Board(Board);
-- Get the move
Put_Line("Select a move:");
Move := Get_Line;
while move /= "Q" loop
Move_From := Integer'Value(Move(Move'First .. Move'First + 1));
Move_To := Integer'Value(Move(Move'First + 3 .. Move'Last));
-- Put_Line(Integer'Image(Move_From) & " to" & Integer'Image(Move_To));
-- Associate the move with a piece
for I in Board'Range(1) loop
for J in Board'Range(1) loop
if Move_From = Board(I)(J).Coordinate then
Move_Piece(Board(I)(J));
end if;
end loop;
end loop;
-- Print the Board
Print_Board(Board);
-- Get the move
Put_Line("Select a move:");
Move := Get_Line;
end loop;
end Chess;
adjust_board.adb:
with Chess_Types;
use Chess_Types;
with Chess_Types.Piece_Types;
use Chess_Types.Piece_Types;
package body Adjust_Board is
procedure Initialize_Board(Board: in out Board_Type) is
-- Define White Chess Pieces
WP1 : Pond := ("wP ", True, White, 12, True);
WP2 : Pond := ("wP ", True, White, 22, True);
WP3 : Pond := ("wP ", True, White, 32, True);
WP4 : Pond := ("wP ", True, White, 42, True);
WP5 : Pond := ("wP ", True, White, 52, True);
WP6 : Pond := ("wP ", True, White, 62, True);
WP7 : Pond := ("wP ", True, White, 72, True);
WP8 : Pond := ("wP ", True, White, 82, True);
WR1 : Rook := ("wRk", True, White, 11);
WR2 : Rook := ("wRk", True, White, 81);
WK1 : Knight := ("wKn", True, White, 21);
WK2 : Knight := ("wKn", True, White, 71);
WB1 : Bishop := ("wBi", True, White, 31);
WB2 : Bishop := ("wBi", True, White, 61);
WQ : Queen := ("wQu", True, White, 41);
WK : King := ("wKi", True, White, 51);
-- Define Black Chess Pieces
BP1 : Pond := ("bP ", True, Black, 17, True);
BP2 : Pond := ("bP ", True, Black, 27, True);
BP3 : Pond := ("bP ", True, Black, 37, True);
BP4 : Pond := ("bP ", True, Black, 47, True);
BP5 : Pond := ("bP ", True, Black, 57, True);
BP6 : Pond := ("bP ", True, Black, 67, True);
BP7 : Pond := ("bP ", True, Black, 77, True);
BP8 : Pond := ("bP ", True, Black, 87, True);
BR1 : Rook := ("bRk", True, Black, 18);
BR2 : Rook := ("bRk", True, Black, 88);
BK1 : Knight := ("bKn", True, Black, 28);
BK2 : Knight := ("bKn", True, Black, 78);
BB1 : Bishop := ("bBi", True, Black, 38);
BB2 : Bishop := ("bBi", True, Black, 68);
BQ : Queen := ("bQu", True, Black, 48);
BK : King := ("bKi", True, Black, 58);
begin
-- Initialize Chess Board
Board(1)(1) := Piece(WR1);
Board(8)(1) := Piece(WR2);
Board(2)(1) := Piece(WK1);
Board(7)(1) := Piece(WK1);
Board(3)(1) := Piece(WB1);
Board(6)(1) := Piece(WB1);
Board(4)(1) := Piece(WQ);
Board(5)(1) := Piece(WK);
Board(1)(2) := Piece(WP1);
Board(2)(2) := Piece(WP2);
Board(3)(2) := Piece(WP3);
Board(4)(2) := Piece(WP4);
Board(5)(2) := Piece(WP5);
Board(6)(2) := Piece(WP6);
Board(7)(2) := Piece(WP7);
Board(8)(2) := Piece(WP8);
Board(1)(8) := Piece(BR1);
Board(8)(8) := Piece(BR2);
Board(2)(8) := Piece(BK1);
Board(7)(8) := Piece(BK1);
Board(3)(8) := Piece(BB1);
Board(6)(8) := Piece(BB1);
Board(4)(8) := Piece(BQ);
Board(5)(8) := Piece(BK);
Board(1)(7) := Piece(BP1);
Board(2)(7) := Piece(BP2);
Board(3)(7) := Piece(BP3);
Board(4)(7) := Piece(BP4);
Board(5)(7) := Piece(BP5);
Board(6)(7) := Piece(BP6);
Board(7)(7) := Piece(BP7);
Board(8)(7) := Piece(BP8);
end Initialize_Board;
end Adjust_Board;
In chess_types.ads, add
type Piece_Acc is access all Piece'Class;
Board_Row needs to be an array of Piece_Acc:
type Board_Row is array (1..8) of Piece_Acc;
You really want the elements in your array to be Piece'Class, but that doesn't work, since the compiler can't tell at that point what types might be derived from Piece and what their memory size is, so it wouldn't be able to set up an array. So it needs to be an access type instead. (In C# or Java, all objects are automatically access types [pointers] whether you want it or not. In Ada you need to tell it when you want things to be pointers.) Then when you set things up in adjust_board.adb, you'd say things like
Board(1)(1) := new Rook' (WR1);
and so on, in order to create the access object.
[Also, this will cause everything else in Board that isn't initialized to be initialized to null. If you want to initialize it to some other Piece that indicates "no piece", you'll need to assign to the unused spaces in the Board yourself.]
But once all that's done, when you say
Board(I)(J).Move_Piece; -- same as Board(I)(J).all.Move_Piece;
or
Move_Piece(Board(I)(J).all);
the type of Board(I)(J).all is a class-wide type, so it will dispatch to the correct Move_Piece like you want.
Note that if when you allocate things yourself with "new", you also have to be responsible for deallocation to avoid memory leaks (unless everything is allocated only once, and then you don't really care). The best way to do that involves controlled types, i.e. making Piece derived from Ada.Finalization.Controlled.
MORE: A way to avoid dealing with the access and allocation/deallocation stuff yourself might be to use Ada.Containers.Indefinite_Vectors instead of an array:
subtype Board_Index is Integer range 1 .. 64;
package Chessboard is new Ada.Containers.Indefinite_Vectors (Board_Index, Piece'Class);
This package doesn't allow multidimensional-type indexes, so you'd need to compute a single index yourself (in the range 1..64 or 0..63), or instantiate Indefinite_Vectors twice which I think is clunky. But this should eliminate the need to do your own allocations, and I think it also does the deallocations for you when the container is destroyed.
Related
I have created a plc program in TwinCat and its saving data into csv file. But variable values are not updating. Only one value is repeating in csv file again and and again. Where I am doing wrong !!! Here is my code:
PROGRAM MAIN
VAR
// Open, close and write function block
fbFileOpen: FB_FileOpen;
fbFileClose: FB_FileClose;
fbFileWrite: FB_FileWrite;
fbFormatString2: FB_FormatString2;
fbGetTime: NT_GetTime;
//file variables
nState : INT := 0;
nCounter : LREAL :=0;
hFile: UINT;
sPathName : T_MaxString;
sWriteBuffer : STRING(5000);
sBufferTemp : STRING(1000);
bBufferTemp : BOOL;
sFormat : STRING(255);
//General Variables
bFill: BOOL;
bWrite: BOOL;
rTimestamp : LREAL;
rCurrent: LREAL;
rActPos: LREAL;
nTimeMilli: INT;
i: ULINT;
END_VAR
// Input values
//------------------------------------------------------------------------------------------------------------------------
rTimestamp:= ULINT_TO_LREAL(F_GetSystemTime());
nCounter:= nCounter+1;
rCurrent:= (nCounter+1)/100;
rActPos:= (nCounter+1)/200;
IF bFill THEN
FOR i :=0 TO 10000000 BY 1 DO
GVL.arrLog[i].rTimestamp := rTimestamp;
GVL.arrLog[i].rCurrent := rCurrent;
GVL.arrLog[i].rActPos := rActPos;
END_FOR
END_IF
// Function Block for Current Date and Time
//------------------------------------------------------------------------------------------------------------------------
IF fbGetTime.START AND NOT fbGetTime.BUSY THEN // simple flip flop for quick update of time
fbGetTime.START := FALSE;
ELSE
fbGetTime.START := TRUE;
END_IF
fbGetTime(
NETID:= ,
START:= ,
TMOUT:= ,
BUSY=> ,
ERR=> ,
ERRID=> ,
TIMESTR=> ); // The TIMESTR is used to get times and dates
//Case Statements that will handle sequence of writing
//------------------------------------------------------------------------------------------------------------------------
CASE nState OF
0: //Wait for write trigger
IF bWrite THEN
nState := 10;
bWrite := FALSE;
END_IF
10: //Create file path and file using date
sPathName := CONCAT('D:\Data\', WORD_TO_STRING(fbGetTime.TIMESTR.wYear));
sPathName := CONCAT(sPathName,'_');
sPathName := CONCAT(sPathName,WORD_TO_STRING(fbGetTime.TIMESTR.wMonth));
sPathName := CONCAT(sPathName,'_');
sPathName := CONCAT(sPathName,WORD_TO_STRING(fbGetTime.TIMESTR.wDay));
sPathName := CONCAT(sPathName,'_');
sPathName := CONCAT(sPathName,WORD_TO_STRING(fbGetTime.TIMESTR.wHour));
sPathName := CONCAT(sPathName,'_');
sPathName := CONCAT(sPathName,WORD_TO_STRING(fbGetTime.TIMESTR.wMinute));
sPathName := CONCAT(sPathName,'_Datalog.csv');
nState:= 20;
fbFileOpen.bExecute := TRUE;
20: //Open and wait for file to open
fbFileOpen.bExecute := TRUE;
IF NOT fbFileOpen.bBusy AND NOT fbFileOpen.bError THEN
fbFileOpen.bExecute := FALSE;
nState := 30;
END_IF
30: // Write contents in file
sWriteBuffer := 'Name, fCurrentScaled, fActPos $n';
sFormat := '%F, %F, %F $n';
nTimeMilli := WORD_TO_INT(fbGetTime.TIMESTR.wMilliseconds);
IF WORD_TO_STRING(fbGetTime.TIMESTR.wMinute) <> INT_TO_STRING(40) THEN
FOR nTimeMilli:= 0 TO 999 BY 1 DO
fbFormatString2(
pFormatString:= ADR(sFormat),
arg1:= F_LREAL(GVL.arrLog[i].rTimestamp),
arg2:= F_LREAL(GVL.arrLog[i].rCurrent),
arg3:= F_LREAL(GVL.arrLog[i].rActPos),
pDstString:= ADR(sWriteBuffer),
nDstSize:= SIZEOF(sWriteBuffer),
bError=> ,
nErrId=> );
bBufferTemp := CONCAT2(pSrcString1 := ADR(sWriteBuffer),
pSrcString2 := ADR(sBufferTemp),
pDstString:= ADR(sWriteBuffer),
nDstSize := SIZEOF(sWriteBuffer));
END_FOR
ELSE
nState := 40;
fbFileWrite.bExecute := TRUE;
END_IF
40: // Write data in file and Wait for writing in the file
fbFileWrite.bExecute := TRUE;
IF NOT fbFileWrite.bBusy AND NOT fbFileWrite.bError THEN
fbFileWrite.bExecute := FALSE;
nState := 50;
fbFileClose.bExecute := TRUE;
END_IF
50: // close file and wait for it to close
fbFileClose.bExecute := TRUE;
IF NOT fbFileClose.bBusy AND NOT fbFileClose.bError THEN
fbFileClose.bExecute := FALSE;
nState:= 0;
END_IF
END_CASE
// FunctionBlocks for OPEN, WRITE and CLOSE
//------------------------------------------------------------------------------------------------------------------------
fbFileOpen(
sNetId:= '', //The netID does not need to be specified for local system
sPathName:= sPathName,
nMode:= FOPEN_MODEAPPEND OR FOPEN_MODEPLUS, // Open empty file for both read and write. If file exists then its content are destroyed
ePath:= PATH_GENERIC,
bExecute:= ,
tTimeout:= ,
bBusy=> ,
bError=> ,
nErrId=> ,
hFile=> hFile); // This file handle will be same for all function blocks.
fbFileClose(
sNetId:= '',
hFile:= hFile,
bExecute:= ,
tTimeout:= ,
bBusy=> ,
bError=> ,
nErrId=> );
fbFileWrite(
sNetId:= '',
hFile:= hFile,
pWriteBuff:= ADR(sWriteBuffer), // A pointer is used to get address
cbWriteLen:= SIZEOF(sWriteBuffer), // Needs to know to size of string going to be written
bExecute:= ,
tTimeout:= ,
bBusy=> ,
bError=> ,
nErrId=> ,
cbWrite=> );
I have created a counter and divided into smaller portion so that I get several values for one second. Is there update syntax I am missing?
The problem would appear to be in your step 30. It looks like you're trying to execute the file write during the 40th minute of the hour, and the rest of the time you're assembling the string to be written. But you have the line sWriteBuffer := 'Name, fCurrentScaled, fActPos $n'; at the beginning of step 30, outside of the conditional block, so it will execute every time.
When the 40th minute occurs and you move to the next step to do the file write, you're still executing that line which will overwrite whatever was put into sWriteBuffer by fbFormatString2. I think the assignment statements for sWriteBuffer and sFormat should be inside the IF statement.
Also, I don't know why you have the line nTimeMilli := WORD_TO_INT(fbGetTime.TIMESTR.wMilliseconds); when you're using nTimeMilli as the index variable in your FOR loop. Is that supposed to be i?
You don't show how bWrite is activated, which starts the state machine, but what if it happened to be triggered right on the 40th minute? Your step 30 would go immediately into the file write without assembling the values to be written.
I am trying to create a structure:
MyTopic
TopicID : String;
HelpID : Integer;
I wanted to create an array of these structures so I could sort them.
I have tried using this type / record syntax but it is failing.
Update
I defined this type and procedure:
type
TMyTopicRecord = record
idTopic : String;
idContextHelp : integer;
End;
procedure GetSortedTopicIDs(aTopics : array of String; size : Integer);
var
aMyTopicRecords : array of TMyTopicRecord;
temp : TMyTopicRecord;
iTopic, i, j : Integer;
begin
// Init the array
SetLength(aMyTopicRecords, size);
// Fill the array with the existing topid ids.
// Get the context ids at the same time.
for iTopic := 0 to size - 1 do
aMyTopicRecords[iTopic].idTopic := aTopics[iTopic];
aMyTopicRecords[iTopic].idContextHelp := HndTopics.GetTopicHelpContext(aTopics[iTopic]);
// Sort the array on context id
for i := size-1 DownTo 1 do
for j := 2 to i do
if (aMyTopicRecords[j-1].idContextHelp > aMyTopicRecords[j].idContextHelp) Then
begin
temp := aMyTopicRecords[j-1];
aMyTopicRecords[j-1] := aMyTopicRecords[j];
aMyTopicRecords[j] := temp;
end;
// Rebuild the original array of topic ids
for iTopic := 0 to size - 1 do
aTopics[iTopic] := aMyTopicRecords[iTopic].idTopic;
end;
The procedure gets called in a loop of the parent function (code snipped):
function GetKeywordsAsHtml(): string;
var
aKeywordList: THndKeywordsInfoArray;
aAssociatedTopics: array of string;
nBlocLevel, nDif, nClose, nCurKeywordLevel, nCurKeywordChildrenCnt: Integer;
nCurKeyword, nCurKeywordTopic: Integer;
nCountAssociatedTopics: Integer;
sCurrentKeyword, sKeywordLink, sKeywordRelated: string;
sKeywordJsCaption: string;
begin
Result := '<ul>';
nBlocLevel := 0;
try
aKeywordList := HndKeywords.GetKeywordList(False);
for nCurKeyword := 0 to length(aKeywordList) - 1 do
begin
sCurrentKeyword := aKeywordList[nCurKeyword].id;
nCurKeywordLevel := HndKeywords.GetKeywordLevel(sCurrentKeyword);
nCurKeywordChildrenCnt := HndKeywords.GetKeywordDirectChildrenCount(sCurrentKeyword);
sKeywordLink := '#';
sKeywordRelated := '[]';
aAssociatedTopics := HndTopicsKeywords.GetTopicsAssociatedWithKeyword(sCurrentKeyword);
nCountAssociatedTopics := Length(aAssociatedTopics);
if nCountAssociatedTopics > 0 then
begin
GetSortedTopicIDs(aAssociatedTopics, nCountAssociatedTopics);
// Code snipped
end;
end;
finally
Result := Result + '</ul>';
end;
end;
The script compiled in the HelpNDoc internal editor with no issues. But when I go to actually build my HTML documentation I encounter a problem:
The HelpNDoc API is explained here.
Is there something wrong with my code?
I decided to go about it a different way and used a simpler technique:
procedure GetSortedTopicIDs(var aTopics : array of String; iNumTopics : Integer);
var
iTopic : Integer;
// List of output
aList: TStringList;
begin
// Init list
aList := TStringList.Create;
// Build a new array of "nnn x"
// - nnn is the help context id
// - x is the topid id
// Note: I know that the context ID values are within the range 0 - 200
for iTopic := 0 to iNumTopics - 1 do
// We pad the context id with 0. We could increase the padding width to
// make the script mre useful
aList.Add(Format('%0.3d %s', [
HndTopics.GetTopicHelpContext(aTopics[iTopic]),
aTopics[iTopic]
]));
// Now we sort the new array (which basically sorts it by context id)
aList.Sort;
// Update original array
for iTopic := 0 to iNumTopics - 1 do
// We ignore the "nnn " part of the string to get just the topic id
aTopics[iTopic] := copy(aList[iTopic],5, length(aList[iTopic])-4);
// Tidy up
aList.Free;
end;
This compiles and I get the sorted array of topic IDs at the end of it. So the pop-up help is now listed as I want.
I have this:
ShellExecute(Application.Handle, nil, PWideChar('explorer.exe'), PWideChar(ImagesDir), nil, SW_SHOWNORMAL);
where the variable ImagesDir is the directory of Images that I want to show by the Windows Explorer...
How can I run the Windows Explorer beside my application at a specified Bounds, for exemple like this?
when you open any File Explorer window (such as going to C:\ ), File Explorer has a specific saved window size that it opens with. So when you resize it, either horizontally and/or vertically, close it and re-open it again, it saves the size of the window, and the location within the Registry where this information is saved is this:
On my system, HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell\WinPos1366x768x96(1)..position, where position is left, right, top or bottom, gives the position of the window border in pixels.
I assume the name of the key depends on the screen resolution.here
and the code will be like that:
.....
const
AMainKey = '\Software\Classes\Local
Settings\Software\Microsoft\Windows\Shell\Bags\AllFolders\Shell\';
var
FrmMain: TFrmMain;
ImagesDir: string;
AWinPos_left, AWinPos_Top,
AWinPos_Right, AWinPos_Bottom: string;
implementation
Uses
ShellApi, Registry;
{$R *.dfm}
procedure ExploreDir_With_Bounds(AFile_Dir: string;ALeft, ATop, AWidth, AHieght: DWORD);
FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
BEGIN
Result :=(ShellExecute(GetDesktopWindow,'open',PWideChar(Dir),'','',SW_SHOW)>32)
END;
var
ListNames, ListPosition: TStringList;
I, AScreen_Width, AScreen_Hieght, APixelPI: Integer;
AWinPos_Uses: string;
begin
ListNames := TStringList.Create;
ListPosition := TStringList.Create;
With TRegistry.Create Do
Try
RootKey := HKEY_CURRENT_USER;
OpenKey(AMainKey,FALSE);
GetValueNames(ListNames);
AScreen_Width := Screen.Width;
AScreen_Hieght := Screen.Height;
APixelPI := Screen.PixelsPerInch;
AWinPos_Uses := 'WinPos'+AScreen_Width.ToString+'x'+AScreen_Hieght.ToString+'x'+APixelPI.ToString;
for I := 0 to ListNames.Count - 1 do
begin
if Pos(AWinPos_Uses, ListNames[I]) <> 0 then
begin
ListPosition.Add(ListNames[I]);
end;
end;
for I := 0 to ListPosition.Count - 1 do
begin
if (Pos('left', ListPosition[I]) <> 0) then
begin
AWinPos_left := ListPosition[I];
Lbl_Left.Caption := AWinPos_left;
Continue;
end else
if (Pos('top', ListPosition[I]) <> 0) then
begin
AWinPos_Top := ListPosition[I];
Lbl_Top.Caption := AWinPos_Top;
Continue;
end else
if (Pos('right', ListPosition[I]) <> 0) then
begin
AWinPos_Right := ListPosition[I];
Lbl_Right.Caption := AWinPos_Right;
Continue;
end else
if (Pos('bottom', ListPosition[I]) <> 0) then
begin
AWinPos_Bottom := ListPosition[I];
Lbl_Bottom.Caption := AWinPos_Bottom;
end;
end;
if (AWinPos_left <> '')and(AWinPos_Top <> '')and
(AWinPos_Right <> '')and(AWinPos_Bottom <> '') then
begin
WriteInteger(AWinPos_left, ALeft);
WriteInteger(AWinPos_Top, ATop);
WriteInteger(AWinPos_Right, ALeft + AWidth);
WriteInteger(AWinPos_Bottom, ATop + AHieght);
end;
CloseKey;
Finally
Free;
ListNames.Free;
ListPosition.Free;
End;
ExploreDirectory(AFile_Dir);
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
ImagesDir := TDirectory.GetParent(TDirectory.GetParent(ExtractFileDir(ParamStr(0))))+ '\My Images To Test';
ExploreDir_With_Bounds(ImagesDir, (50 + Width)+10{Left}, 50{TOP},
Screen.Width - (Left + Width +20){width},
Screen.Height - 150{hieght});
end;
procedure TFrmMain.FormShow(Sender: TObject);
begin
Left := 0;
Top := (Screen.WorkAreaHeight div 2)-(Height div 2);
end;
end.
the Result here
You can use the following function to open an explorer window and have it point to a specific directory.
USES Windows,ShellAPI;
FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
BEGIN
Result:=(ShellExecute(GetDesktopWindow,'open',PChar(Dir),'','',SW_SHOW)>32)
END;
Note, however, that you can't (with this code) make the Explorer window "follow" your program, ie. the opened window is a completely autonomous window that has no link to your program, just as if the user had browsed to the directory himself. If you call this function again with a new directory, Explorer will open a new window with that directory (and keep the old one opened).
UPDATE:
If you want to be able to manipulate the explorer window after it is opened, you need to use the various interfaces that Explorer exposes. I have made a UNIT that allows you to do what you seek as well as returning the interface needed to be able to manipulate the window afterwards. It is heavily based on the code found in this answer:
Check if windows explorer already opened on given path
by Victoria
UNIT WindowsExplorer;
INTERFACE
USES Types,ShDocVw;
FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
FUNCTION OpenFolder(CONST Dir : STRING) : IWebBrowserApp; OVERLOAD;
FUNCTION OpenFolderAt(CONST Dir : STRING ; Left,Top,Width,Height : INTEGER) : IWebBrowserApp; OVERLOAD;
FUNCTION OpenFolderAt(CONST Dir : STRING ; CONST Rect : TRect) : IWebBrowserApp; OVERLOAD; INLINE;
IMPLEMENTATION
USES Windows,Variants,ShlObj,Ole2,OleAuto,ShellAPI,ActiveX,SysUtils;
FUNCTION ExploreDirectory(CONST Dir : STRING) : BOOLEAN;
BEGIN
Result:=(ShellExecute(GetDesktopWindow,'open',PChar(Dir),'','',SW_SHOW)>32)
END;
FUNCTION GetFolderIDList(CONST Dir : STRING) : PItemIDList;
VAR
ShellFolder : IShellFolder;
Attributes : ULONG;
Count : ULONG;
BEGIN
OleCheck(SHGetDesktopFolder(ShellFolder));
Attributes:=SFGAO_FOLDER or SFGAO_STREAM;
OleCheck(ShellFolder.ParseDisplayName(0,NIL,PWideChar(WideString(Dir)),Count,Result,Attributes));
IF NOT ((Attributes AND SFGAO_FOLDER=SFGAO_FOLDER) AND (Attributes AND SFGAO_STREAM<>SFGAO_STREAM)) THEN BEGIN
CoTaskMemFree(Result);
Result:=NIL
END
END;
FUNCTION OpenFolder(CONST Dir : STRING ; OpenIfNotFound : BOOLEAN) : IWebBrowserApp; OVERLOAD;
CONST
IID_IServiceProvider: System.TGUID = '{6D5140C1-7436-11CE-8034-00AA006009FA}';
VAR
FolderID : PItemIDList;
ShellWindows : IShellWindows;
I : INTEGER;
WndIFace : System.IDispatch;
WebBrowserApp : IWebBrowserApp;
ServiceProvider : IServiceProvider;
ShellBrowser : IShellBrowser;
ShellView : IShellView;
FolderView : IFolderView;
PersistFolder : IPersistFolder2;
CurFolderID : PItemIDList;
BEGIN
FolderID:=GetFolderIDList(Dir);
IF Assigned(FolderID) THEN TRY
OleCheck(CoCreateInstance(CLASS_ShellWindows,NIL,CLSCTX_LOCAL_SERVER,IID_IShellWindows,ShellWindows));
FOR I:=0 TO PRED(ShellWindows.Count) DO BEGIN
WndIface:=ShellWindows.Item(VarAsType(I,VT_I4));
IF Assigned(WndIface) AND
Succeeded(WndIface.QueryInterface(IID_IWebBrowserApp,WebBrowserApp)) AND
Succeeded(WebBrowserApp.QueryInterface(IID_IServiceProvider,ServiceProvider)) AND
Succeeded(ServiceProvider.QueryService(SID_STopLevelBrowser,IID_IShellBrowser,ShellBrowser)) AND
Succeeded(ShellBrowser.QueryActiveShellView(ShellView)) AND
Succeeded(ShellView.QueryInterface(IID_IFolderView,FolderView)) AND
Succeeded(FolderView.GetFolder(IID_IPersistFolder2,PersistFolder)) AND
Succeeded(PersistFolder.GetCurFolder(CurFolderID)) AND
ILIsEqual(FolderID,CurFolderID) THEN BEGIN
IF IsIconic(WebBrowserApp.HWnd) THEN Win32Check(ShowWindow(WebBrowserApp.HWnd,SW_RESTORE));
Win32Check(SetForegroundWindow(WebBrowserApp.HWnd));
Exit(WebBrowserApp)
END
END
FINALLY
CoTaskMemFree(FolderID)
END;
Result:=NIL;
IF OpenIfNotFound THEN BEGIN
IF NOT ExploreDirectory(Dir) THEN EXIT;
FOR I:=1 TO 20 DO BEGIN
Result:=OpenFolder(Dir,FALSE);
IF Assigned(Result) THEN EXIT;
Sleep(100)
END
END
END;
FUNCTION OpenFolder(CONST Dir : STRING) : IWebBrowserApp;
BEGIN
Result:=OpenFolder(Dir,TRUE)
END;
FUNCTION OpenFolderAt(CONST Dir : STRING ; Left,Top,Width,Height : INTEGER) : IWebBrowserApp;
BEGIN
Result:=OpenFolder(Dir);
IF Assigned(Result) THEN BEGIN
Result.Left:=Left; Result.Top:=Top; Result.Width:=Width; Result.Height:=Height
END
END;
FUNCTION OpenFolderAt(CONST Dir : STRING ; CONST Rect : TRect) : IWebBrowserApp;
BEGIN
Result:=OpenFolderAt(Dir,Rect.Left,Rect.Top,Rect.Width,Rect.Height)
END;
END.
It is made for use with Delphi Tokyo 10.2.3 so if you use an earlier version (you didn't specify Delphi version in your question), you may need to adapt the USES list to match.
I use this example to send a string between two applications.
When I press the Send button for the first time, the string is sent to the Receiver, but only a part of the string is received.
When I press the Send button for the second time, I get "Window not found!".
The window is right there on screen. Why it works when I press the button the first time, but not the second time?
This is the sender:
procedure TfrmSender.SendString;
var
stringToSend : string;
copyDataStruct : TCopyDataStruct;
begin
Caption:= 'Sending';
stringToSend := 'About - Delphi - Programming';
copyDataStruct.dwData := 12821676; //use it to identify the message contents
copyDataStruct.cbData := 1 + Length(stringToSend) ;
copyDataStruct.lpData := PChar(stringToSend);
SendData(copyDataStruct) ;
end;
procedure TfrmSender.SendData(CONST copyDataStruct: TCopyDataStruct);
VAR
receiverHandle : THandle;
res : integer;
begin
receiverHandle := FindWindow(PChar('TfrmReceiver'), PChar('frmReceiver')) ;
if receiverHandle = 0 then
begin
Caption:= 'Receiver window NOT found!';
EXIT;
end;
res:= SendMessage(receiverHandle, WM_COPYDATA, Integer(Handle), Integer(#copyDataStruct));
if res= 0 then Caption:= 'Receiver window found but msg not hand';
end;
And this is the receiver:
procedure TfrmReceiver.WMCopyData(var Msg: TWMCopyData);
VAR
s : string;
begin
if Msg.CopyDataStruct.dwData = 12821676 then
begin
s := PChar(Msg.CopyDataStruct.lpData);
msg.Result := 2006; //Send something back
Winapi.Windows.Beep(800, 300);
Caption:= s;
end
end;
To summarize the comments there are two errors
1) (See #Tom Brunberg) is that the length is set incorrectly which is why you only get part (about half? of the string)
It should be
copyDataStruct.cbData := sizeof( Char )*(Length(stringToSend) + 1 );
2) The forms caption is being changed which invalidates the expression
FindWindow(PChar('TfrmReceiver'), PChar('frmReceiver'))
because the second parameter is the form's caption (in Delphi terminology)
I have simple "RAM" implemented as:
type memory_array is array(31 downto 0) of std_logic_vector(7 downto 0);
signal ram : memory_array;
I would like to init it's content from HEX file. I wonder about reading the file like:
ram_init: process
file file_ptr : text;
variable line_text : string(1 to 14);
variable line_num : line;
variable lines_read : integer := 0;
variable char : character;
variable tmp_hexnum : string(1 to 2);
begin
file_open(file_ptr,"../RAM.HEX",READ_MODE);
while (not endfile(file_ptr)) loop
readline (file_ptr,line_num);
READ (line_num,line_text);
if (lines_read < 32) then
tmp_hexnum := line_text(10 to 11);
-- ram(lines_read) <= tmp_hexnum;
lines_read := lines_read + 1;
wait for 10 ns;
end if;
end loop;
file_close(file_ptr);
wait;
end process;
The problem is (if this code above would works, which I don't even know), how to convert the tmp_hexnum string to std_logic_vector.
Please have patience with me, VHDL beginner.
The first mistake is to use a process : if you attempt to synthesise the design, the process won't do anything until the design is built and running; which is far too late to read a file!
Instead, wrap the init code in a function, and use that to initialise the memory
signal ram : memory_array := my_ram_init(filename => "../RAM.HEX");
This will work in simulation, and many synthesis tools will infer a RAM and initialise it correctly. If you declared a constant instead of a signal, this would create a ROM instead of a RAM.
Anyway the function looks a bit like
function my_ram_init(filename : string) return memory_array is
variable temp : memory_array;
-- other variables
begin
file_open(...);
-- you have a good handle on the function body
file_close(...);
return temp;
end function;
leaving you with the original problem :
temp(lines_read) <= to_slv(tmp_hexnum);
writing the to_slv function. There ought to be a standard library of these, but for some reason there isn't a universally accepted one. So, here's a start...
function to_slv (tmp_hexnum : string) return std_logic_vector is
variable temp : std_logic_vector(7 downto 0);
variable digit : natural;
begin
for i in tmp_hexnum'range loop
case tmp_hexnum(i) is
when '0' to '9' =>
digit := Character'pos(tmp_hexnum(i)) - Character'pos('0');
when 'A' to 'F' =>
digit := Character'pos(tmp_hexnum(i)) - Character'pos('A') + 10;
when 'a' to 'f' =>
digit := Character'pos(tmp_hexnum(i)) - Character'pos('a') + 10;
when others => digit := 0;
end case;
temp(i*4+3 downto i*4) := std_logic_vector(to_unsigned(digit));
end loop;
return temp;
end function;
Converting a string of variable length to std_logic_vector with length as 4 *
length of string, can be done with the function below:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
...
-- Convert string to std_logic_vector, assuming characters in '0' to '9',
-- 'A' to 'F', or 'a' to 'f'.
function str_to_slv(str : string) return std_logic_vector is
alias str_norm : string(1 to str'length) is str;
variable char_v : character;
variable val_of_char_v : natural;
variable res_v : std_logic_vector(4 * str'length - 1 downto 0);
begin
for str_norm_idx in str_norm'range loop
char_v := str_norm(str_norm_idx);
case char_v is
when '0' to '9' => val_of_char_v := character'pos(char_v) - character'pos('0');
when 'A' to 'F' => val_of_char_v := character'pos(char_v) - character'pos('A') + 10;
when 'a' to 'f' => val_of_char_v := character'pos(char_v) - character'pos('a') + 10;
when others => report "str_to_slv: Invalid characters for convert" severity ERROR;
end case;
res_v(res_v'left - 4 * str_norm_idx + 4 downto res_v'left - 4 * str_norm_idx + 1) :=
std_logic_vector(to_unsigned(val_of_char_v, 4));
end loop;
return res_v;
end function;
Your (both) answers helped me a lot. But it seems not working.
function ram_init(filename : string) return memory_array is
variable temp : memory_array;
file file_ptr : text;
variable line_line : line;
variable line_text : string(1 to 14);
variable tmp_hexnum : string(1 to 2);
variable lines_read : integer := 0;
begin
file_open(file_ptr,filename,READ_MODE);
while (lines_read < 32 and not endfile(file_ptr)) loop
readline (file_ptr,line_line);
read (line_line,line_text);
tmp_hexnum := line_text(10 to 11);
temp(lines_read) := hex_to_bin(tmp_hexnum);
lines_read := lines_read + 1;
end loop;
file_close(file_ptr);
return temp;
end function;
signal ram : memory_array := ram_init(filename=>"../RAM.HEX");
If I set tmp_hexnum to e.g. "0A", it's OK, but reading from file do not fill the RAM.
Can you please check the file part for me, too?