Re: winapi, dll

2020-10-15 Thread John Chapman via Digitalmars-d-learn

On Thursday, 15 October 2020 at 20:13:37 UTC, Atmosfear wrote:

On Thursday, 15 October 2020 at 16:32:06 UTC, Imperatorn wrote:

On Thursday, 15 October 2020 at 12:45:42 UTC, Atmosfear wrote:
I didn't find how to call the queryperformancecounter 
function. I tried this. Returns errors, doesn't know what 
BOOL and LARGE_INTEGER are.


import core.sys.windows.windows;
import core.sys.windows.w32api;
import core.sys.windows.winbase;
pragma(lib, "kernel32");
extern (Windows)
{
BOOL QueryPerformanceCounter(LARGE_INTEGER 
*lpPerformanceCount);

}
void main()
{}


It's already defined. Just use QueryPerformanceCounter, (no 
extern).


I'm a newby. Can you show me an example? In which module is it?


Just import core.sys.windows.windows and call the function like 
so:


---
import core.sys.windows.windows;

void main() {
  LARGE_INTEGER pc;
  QueryPerformanceCounter();
}
---


Re: I need "windowsx.d" Someone can send It to me?

2020-09-26 Thread John Chapman via Digitalmars-d-learn

On Friday, 25 September 2020 at 15:03:56 UTC, Marcone wrote:
I need windowsx.d but for I don't know the reason is not in 
dmd. Someone that have it can send to me? I don't know convert 
windowsx.h to windowsx.d


windowsx.h is mostly a bunch of macros that forward to functions 
elsewhere in the SDK. Yes, it's handy, but you can get by without 
it in case you don't manage to get it translated to D. Open 
windowsx.h in your editor, find the macro you want to use, look 
across to the right to see what the macro expands to, and use 
that in your code instead.


A lot of the macros that simply cast between HBITMAP, HPALETTE, 
HFONT, HPEN, HGDIOBJ etc are redundant because in D they're all 
just aliases for void*.


Re: Access violation when using IShellFolder2

2020-09-10 Thread John Chapman via Digitalmars-d-learn

On Thursday, 10 September 2020 at 13:30:15 UTC, FreeSlave wrote:
Thanks. I tried this, but VarDateFromStr does not succeed for 
me.


It turns out the shell embeds some control characters in the 
string, specifically 8206 and 8207. So remove those before 
passing it to VarDateFromStr.


auto temp = strRet.pOleStr[0 .. lstrlenW(strRet.pOleStr)]
  .replace(cast(wchar)8206, "")
  .replace(cast(wchar)8207, "");
DATE date;
VarDateFromStr((temp ~ '\0').ptr, LOCALE_USER_DEFAULT, 0, );



Re: Access violation when using IShellFolder2

2020-09-10 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 9 September 2020 at 22:44:50 UTC, FreeSlave wrote:
Btw do you know how to parse a date returned by GetDetailsOf? 
Couldn't find any examples in C++. I actually can see digits 
representing date and time as a part of the string, but I would 
prefer to use some winapi function to translate it into some 
time type instead of manually parsing the result.


You could look at passing the str.pOleStr field in the 
SHELLDETAILS you got from GetDetailsOf to VarDateFromStr. It will 
give you a DATE value that VariantTimeToSystemTime will convert 
to a SYSTEMTIME from which you can get the years, months, days 
etc.


For example:

SHELLDETAILS details;
GetDetailsOf(pidl, 3, );
DATE date;
VarDateFromStr(details.str.pOleStr, LOCALE_USER_DEFAULT, 0, 
);

SYSTEMTIME st;
VariantTimeToSystemTime(date, );
auto year = st.wYear;
auto month = st.wMonth;

You can convert that into a more D-friendly SysTime object using 
SYSTEMTIMEToSysTime from the std.datetime package.


Re: Access violation when using IShellFolder2

2020-09-09 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 8 September 2020 at 22:24:22 UTC, FreeSlave wrote:
However if I change the type of recycleBin variable to 
IShellFolder (not IShellFolder2), the crash does not happen.


Does IShellFolder2 require some special handling?


The issue is caused by druntime's definition of IShellFolder2. To 
fix it temporarily, just redefine it in your module somewhere:


interface IShellFolder2 : IShellFolder {
  HRESULT GetDefaultSearchGUID(GUID*);
  HRESULT EnumSearches(IEnumExtraSearch*);
  HRESULT GetDefaultColumn(DWORD, ULONG*, ULONG*);
  HRESULT GetDefaultColumnState(UINT, SHCOLSTATEF*);
  HRESULT GetDetailsEx(LPCITEMIDLIST, const(SHCOLUMNID)*, 
VARIANT*);

  HRESULT GetDetailsOf(LPCITEMIDLIST, UINT, SHELLDETAILS*);
  HRESULT MapColumnToSCID(UINT, SHCOLUMNID*);
}

IShellFolder2 isn't the only culprit - IShellView2 will need 
fixing too if you intend to use it. There are probably others as 
well.




Re: final switch problem

2020-06-13 Thread John Chapman via Digitalmars-d-learn

On Saturday, 13 June 2020 at 15:33:55 UTC, Boris Carvajal wrote:

On Saturday, 13 June 2020 at 09:02:21 UTC, John Chapman wrote:
Is this a bug or have I made a mistake? This worked a few days 
ago and I haven't changed my setup since then.


https://issues.dlang.org/show_bug.cgi?id=19548

Your code triggers it by using "-debug" option on 
https://run.dlang.io/ using DMD


Hmm, compiling with -release makes it work. Not a huge issue, 
I'll just avoid final switches in debug mode until it's fixed. 
Thanks.


final switch problem

2020-06-13 Thread John Chapman via Digitalmars-d-learn
If I use a final switch and import std.uni (or any other module 
that imports it, such as std.string), I'm getting unresolved 
external symbol errors with DMD 2.092.


This code triggers the issue:

---
module test;

import std.uni;

enum Cheese { cheddar, edam }

void test(Cheese cheese) {
  final switch (cheese) {
  case Cheese.cheddar: break;
  case Cheese.edam: break;
  }
}

void main() {
  test(Cheese.cheddar);
}
---

error LNK2019: unresolved external symbol "pure nothrow @nogc 
@safe void 
core.internal.switch_.__switch_error!().__switch_error(immutable(char)[], ulong)" (_D4core8internal7switch___T14__switch_errorZQrFNaNbNiNfAyamZv) referenced in function _Dmain


If I remove "final" and add a default case, it compiles fine. Is 
this a bug or have I made a mistake? This worked a few days ago 
and I haven't changed my setup since then.


Re: How to get the pointer of "this" ?

2020-05-26 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 26 May 2020 at 13:37:22 UTC, Vinod K Chandran wrote:

On Tuesday, 26 May 2020 at 12:41:20 UTC, John Chapman wrote:

On Monday, 25 May 2020 at 16:26:31 UTC, Vinod K Chandran wrote:

Here is my full code. Please take a look.
https://pastebin.com/av3nrvtT


Change line 124 to:

SetWindowSubclass(this.mHandle, SUBCLASSPROC(), 
UINT_PTR(subClsID), cast(DWORD_PTR)cast(void*)this);


That is, change `` to `cast(void*)this`.


Hi,
Thanks for the reply. That will work like charm but we need to 
change the code in subclassed button's WndProc  like this--

extern(Windows)
private LRESULT btnWndProc(HWND hWnd, UINT message, WPARAM 
wParam, LPARAM lParam, UINT_PTR scID, DWORD_PTR refData) {

try  {

Button thisBtn = cast(Button)cast(void*)refData;
 {
catch (Exception e) {}



Yes, that should work.


Re: How to get the pointer of "this" ?

2020-05-26 Thread John Chapman via Digitalmars-d-learn

On Monday, 25 May 2020 at 16:26:31 UTC, Vinod K Chandran wrote:

Here is my full code. Please take a look.
https://pastebin.com/av3nrvtT


Change line 124 to:

SetWindowSubclass(this.mHandle, SUBCLASSPROC(), 
UINT_PTR(subClsID), cast(DWORD_PTR)cast(void*)this);


That is, change `` to `cast(void*)this`.


Overload function template for rectangular array

2020-05-25 Thread John Chapman via Digitalmars-d-learn
Is it possible to overload a function template for rectangular 
arrays? Is there any way to tell them apart from normal ones?


void foo(T)(T[] a) {}
void foo(T)(T[][] a) {}

auto ra = new int[][](5, 5);
ra.foo(); // matches both

Thanks for any hints.


Re: Easy way to format int in pragma msg ?

2020-05-14 Thread John Chapman via Digitalmars-d-learn

On Thursday, 14 May 2020 at 09:49:15 UTC, wjoe wrote:
Is there an easy way to print an int in hexadecimal, octal or 
binary representation ?


The documentation on pragma(msg, ...) and a quick web search 
didn't provide an answer.


  import std.string;
  pragma(msg, format("%x", 10));

%x = hex
%o = octal
%b = binary


Re: Win32 Api: How create Open/"Save as" Dialog?

2020-01-11 Thread John Chapman via Digitalmars-d-learn

On Saturday, 11 January 2020 at 10:34:34 UTC, Marcone wrote:

This code works, but I can't get file Path. Someone can help me?

import std;
import core.sys.windows.windows;
pragma(lib, "comdlg32");

void main(){
OPENFILENAME ofn;
wchar* szFileName;


You need to supply a buffer, not a pointer:

  wchar[MAX_PATH] szFileName;


(cast(byte*)& ofn)[0 .. ofn.sizeof] = 0;
ofn.lStructSize = ofn.sizeof;
ofn.hwndOwner = null;


The above lines are unnecessary as D structs are automatically 
initialized and lStructSize is already filled in.


ofn.lpstrFilter = "Text Files (*.txt)\0*.txt\0All Files 
(*.*)\0*.*\0";

ofn.lpstrFile = szFileName;


It wants a pointer to your buffer:

  ofn.lpstrFile = szFileName.ptr;


ofn.nMaxFile = MAX_PATH;
ofn.Flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | 
OFN_HIDEREADONLY;

ofn.lpstrDefExt = "txt";
if(GetOpenFileNameW()){
  writeln(szFileName); // Print null
  writeln(ofn.lpstrFile); // Print null


You'll need to slice the buffer to the right length:

  import core.stdc.wchar_ : wcslen;
  writeln(ofn.lpstrFile[0 .. wcslen(ofn.lpstrFile.ptr)]);


}
}





Re: ... use of ... is hidden by ...; use alias ... to introduce base class overload set ??

2019-10-21 Thread John Chapman via Digitalmars-d-learn

On Sunday, 20 October 2019 at 21:45:35 UTC, Robert M. Münch wrote:

class myWidget : Observer!message {...}

class FilterSubject : SubjectObject!message {
 Disposable subscribe(myWidget observer){...}
}


I tried to add "alias subscribe = SubjectObject.subscribe;" in 
different places, but that didn't help. Nor do I have any how 
that should help...


This should work:

class FilterSubject : SubjectObject!message {
  alias subscribe = typeof(super).subscribe;
  Disposable subscribe(myWidget observer){...}
}


Re: What is the alternative to the setlocale function of c in D? Thank you.

2019-01-28 Thread John Chapman via Digitalmars-d-learn

On Sunday, 27 January 2019 at 16:23:42 UTC, FrankLike wrote:

On Sunday, 27 January 2019 at 10:44:04 UTC, John Chapman wrote:

On Sunday, 27 January 2019 at 06:14:15 UTC, FrankLike wrote:
On Saturday, 26 January 2019 at 09:33:33 UTC, John Chapman 
wrote:




What has that code got to do with setting the console's 
font? So you need to add more code to accomplish that.


You don't need to set the font to achieve the goal, why not?


This should work:

const(char)[] toCodePage(const(char)[] s, uint codePage = 0) {
  import core.sys.windows.winnls, std.utf;

  foreach (char c; s) {
if (c >= 0x80) {
  auto temp = s.toUTF16z();
  char[] result;
  if ((result.length = WideCharToMultiByte(codePage, 0, 
temp, -1, null, 0, null, null)) != 0)
WideCharToMultiByte(codePage, 0, temp, -1, result.ptr, 
cast(int)result.length, null, null);

  return result;
}
  }
  return s;
}

void main() {
  import core.sys.windows.wincon, std.stdio;

  SetConsoleOutputCP(936); // Simplified Chinese codepage
  writeln("字符".toCodePage(936));
}

Yes.

extern(C) int setlocale(int,char*);

static this()
{
import core.stdc.wchar_;
import core.stdc.stdio;
fwide(core.stdc.stdio.stdout,1);
setlocale(0,cast(char*)"china");
}
///
it's simple than yours,and don't need convert every string,why 
not work after D2.0.78.1?


I've no idea, sorry. A quick scan of D's changelogs between those 
versions doesn't reveal anything relevant. But I wonder how your 
code ever worked - on Windows, calling setlocale with "china" 
returns null, which means it's not a valid locale, so did nothing.


This does the right thing:

  extern(C) int _cwprintf(const(wchar)*, ...);

  void main() {
SetConsoleOutputCP(936);
_cwprintf("字符\n");
  }


Re: What is the alternative to the setlocale function of c in D? Thank you.

2019-01-27 Thread John Chapman via Digitalmars-d-learn

On Sunday, 27 January 2019 at 06:14:15 UTC, FrankLike wrote:
On Saturday, 26 January 2019 at 09:33:33 UTC, John Chapman 
wrote:


What has that code got to do with setting the console's font? 
So you need to add more code to accomplish that.


You don't need to set the font to achieve the goal, why not?


This should work:

const(char)[] toCodePage(const(char)[] s, uint codePage = 0) {
  import core.sys.windows.winnls, std.utf;

  foreach (char c; s) {
if (c >= 0x80) {
  auto temp = s.toUTF16z();
  char[] result;
  if ((result.length = WideCharToMultiByte(codePage, 0, temp, 
-1, null, 0, null, null)) != 0)
WideCharToMultiByte(codePage, 0, temp, -1, result.ptr, 
cast(int)result.length, null, null);

  return result;
}
  }
  return s;
}

void main() {
  import core.sys.windows.wincon, std.stdio;

  SetConsoleOutputCP(936); // Simplified Chinese codepage
  writeln("字符".toCodePage(936));
}


Re: What is the alternative to the setlocale function of c in D? Thank you.

2019-01-26 Thread John Chapman via Digitalmars-d-learn

On Saturday, 26 January 2019 at 06:03:25 UTC, FrankLike wrote:

On Friday, 25 January 2019 at 15:05:50 UTC, John Chapman wrote:

On Friday, 25 January 2019 at 14:23:15 UTC, FrankLike wrote:
I need to set the font by the code now, because I need to do 
the installer, can't let this installer set the properties on 
each computer?


SetCurrentConsoleFontEx perhaps?

https://docs.microsoft.com/en-us/windows/console/setcurrentconsolefontex


That's so much code than next code.

///
extern(C) int setlocale(int,char*);

static this()
{
import core.stdc.wchar_;
import core.stdc.stdio;
fwide(core.stdc.stdio.stdout,1);
setlocale(0,cast(char*)"china");
}
///
But After D2.078.1,it's not work.
Why?
Thank you.


What has that code got to do with setting the console's font? So 
you need to add more code to accomplish that.


Re: What is the alternative to the setlocale function of c in D? Thank you.

2019-01-25 Thread John Chapman via Digitalmars-d-learn

On Friday, 25 January 2019 at 14:23:15 UTC, FrankLike wrote:
I need to set the font by the code now, because I need to do 
the installer, can't let this installer set the properties on 
each computer?


SetCurrentConsoleFontEx perhaps?

https://docs.microsoft.com/en-us/windows/console/setcurrentconsolefontex



Re: How to split strings into AA using phobos

2018-12-11 Thread John Chapman via Digitalmars-d-learn
On Tuesday, 11 December 2018 at 08:20:32 UTC, Arun Chandrasekaran 
wrote:
A typical example would be to split the HTTP query string into 
an AA.


vibe.d has req.queryString, but no convenient wrapper to access 
it as an AA.


http://localhost/hello?name=abc=123

I've got this far.

auto arr = req.queryString.splitter('&').map!(a => 
a.splitter('='));


Thanks


req.queryString[req.queryString.indexOf('?') + 1 .. $]
  .splitter('&')
  .map!(a => a.splitter('='))
  .map!(a => tuple(a.front, a.back))
  .assocArray


Re: ElementType of MapResult is a delegate??

2018-12-08 Thread John Chapman via Digitalmars-d-learn

On Saturday, 8 December 2018 at 13:02:00 UTC, Yuxuan Shui wrote:

This surprised me A LOT:

https://d.godbolt.org/z/82a_GZ

So if I call something.map!().array, I get an array of 
delegates? That makes no sense to me.


But in your example, "(a) =>" returns "{return tmp;}", which is a 
delegate. Just write "(a) => tmp", or invoke the delegate by 
turning it into a call: "{return tmp;}()".


Ambiguous virtual function

2018-12-05 Thread John Chapman via Digitalmars-d-learn

I get an "ambiguous virtual function" error when I compile this:

  interface I {
void fun();
  }

  mixin template F() {
void fun() {}
  }

  class C : I {
mixin F;
mixin F;
  }

But the error doesn't occur with this:

  class C : I {
mixin F;
void fun() {}
  }

Is the compiler giving the non-mixed-in function special 
treatment?


Re: Function signature as string

2018-11-29 Thread John Chapman via Digitalmars-d-learn
On Thursday, 29 November 2018 at 21:31:57 UTC, Neia Neutuladh 
wrote:

On Thu, 29 Nov 2018 21:11:06 +, John Chapman wrote:
Is there any way to get a string representing a function's 
exact signature as declared in the source? I can generate it 
myself using reflection but it might not be 100% verbatim so 
wanted to know if there's anything built in?


   foreach (m; __traits(allMembers, T)) {
 alias member = __traits(getMember, T, m);
 string signature = // Call some function to get "member"'s
signature as a string
   }


typeof().stringof should do it:

void bar(string s, ref Foo!int i) {}
void main()
{
writeln(typeof().stringof);
}

prints: void function(string s, ref Foo!int i)


That does the trick - thanks.


Function signature as string

2018-11-29 Thread John Chapman via Digitalmars-d-learn
Is there any way to get a string representing a function's exact 
signature as declared in the source? I can generate it myself 
using reflection but it might not be 100% verbatim so wanted to 
know if there's anything built in?


  foreach (m; __traits(allMembers, T)) {
alias member = __traits(getMember, T, m);
string signature = // Call some function to get "member"'s 
signature as a string

  }


Re: How to center dlangui Window on screen

2018-11-29 Thread John Chapman via Digitalmars-d-learn
On Thursday, 29 November 2018 at 13:42:28 UTC, greatsam4sure 
wrote:
Which class in dlangui is use to obtain the screen height and 
width?
A Windom of dimension 280 x 445 in dlangui is the same as a 
Windom of 350 x 550 in Javafx and adobe air.


What could be responsible for this wide difference?
A window of 350 x 550 in adobe air is the same as a window of 
350 x 550 in javafx. So why is dlangui window bigger?


Note that I  am using  w x h for my window dimension and I am 
on windows 10


That looks like DPI scaling is in effect: 280 pixels + 125% DPI = 
350.


There's an example of how to get the screen size here (look for 
getScreenDimensions): 
https://github.com/buggins/dlangui/blob/60159c61e27d86012fbf8f205c75d30196fc0e52/src/dlangui/platforms/windows/winapp.d


Re: Making external types available to mixins

2018-11-24 Thread John Chapman via Digitalmars-d-learn

On Friday, 23 November 2018 at 21:49:55 UTC, Kagamin wrote:
Well, just have all factories in one module and import it, then 
they will be visible.


They're part of another library over which I have no control, but 
yes, I could still import them all and make life easier.



import allfactories;
auto makeWith(string className, Args…)(auto ref Args args) {
  mixin("return makeWith!(I", className, "Factory)(args);"); // 
Fowarded to implementation of makeWith below

}

Or predeclare make functions in factory modules

interface ICalendarFactory
{
  ...
}

alias makeCalendar=makeWith!ICalendarFactory;





Re: memoize & __traits(compiles...)

2018-11-23 Thread John Chapman via Digitalmars-d-learn
On Friday, 23 November 2018 at 11:29:24 UTC, Nicholas Wilson 
wrote:
No, std.functional.memoize uses a hashtable to cache the 
runtime results of calls to expensive functions.


assuming that the example is not oversimplified and 
generateFunc1 and generateFunc2 are functions, the compiler 
doesn't do extra semantic analysis so the validity of the 
functions is effectively cached.


If they are templates (with parameters) then the compiler will 
automatically memoize them (it too keeps a hashtable of 
template instances).


Ah, that's good to know.


memoize & __traits(compiles...)

2018-11-23 Thread John Chapman via Digitalmars-d-learn
I'm doing a fair amount of repeatedly checking if a function 
compiles with __traits(compiles...), executing the function if 
so, erroring out if not, like this:


  static if (__traits(compiles, generateFunc1())) {
return generateFunc1();
  } static if (__traits(compiles, generateFunc2())) {
return generateFunc2();
  } else static assert(false);

But it seems inefficient to have to evaluate those functions 
twice, so I'd like to optimise this so if __traits(compiles...) 
succeeds, the result is cached and then used when the function is 
actually called. I wondered if using std.functional.memoize would 
help?


Re: Making external types available to mixins

2018-11-23 Thread John Chapman via Digitalmars-d-learn
On Thursday, 22 November 2018 at 16:27:08 UTC, Eduard Staniloiu 
wrote:

So I had a go at this and I have a working solution.
https://run.dlang.io/is/oaH6Ib

At first, I tried to do everything in the mixin, as you can see 
with the `failedAttempt` function. The idea was that this 
should have worked like `mixin(failedAttempt!"Calendar"(1, 2, 
3));`. As you can see, and the name suggests, I wasn't able to 
make it work with `args`.


The solution I have to your problem is to use a template, in 
this case the `theType` template that will expand to the fully 
qualified name. So you'd use it like

`makeWith!(theType!"Calendar")(args);`

Hope it helps!

Edi


Thanks!


Re: task can't take a class method

2018-11-19 Thread John Chapman via Digitalmars-d-learn

On Monday, 19 November 2018 at 16:29:01 UTC, helxi wrote:

On Monday, 19 November 2018 at 16:10:15 UTC, helxi wrote:

...


Oh wait never mind I was missing a bracket:

auto proc = task!(ddCall.dd());

Now I have another thing to worry about: ddcall.dd() cannot be 
read at compile time.


You're attempting to execute "dd" at compile time. You should be 
able to pass the function to a task in a couple of ways:


1) task()
2) task!(ddCall.dd)



Re: Making external types available to mixins

2018-11-18 Thread John Chapman via Digitalmars-d-learn
On Saturday, 17 November 2018 at 21:11:38 UTC, Adam D. Ruppe 
wrote:
On Saturday, 17 November 2018 at 17:58:54 UTC, John Chapman 
wrote:

Has anyone had a similar need and come up with a solution?


You might be able to just pass it the Calendar type, and then 
fetch its parent module and get the ICalendarFactory from there 
(assuming they are defined in the same module).


But generally speaking, passing strings to a mixin that refer 
to something in another module isn't going to work well thanks 
to scoping rules. You are better off passing a symbol of some 
sort.


So there is no actual Calendar type. There's an ICalendarFactory 
type that creates instances of ICalendar (these types are part of 
a third-party API).  "Calendar" is just a key users could use 
when calling a "makeWith" method that would build the 
ICalendar/Factory names, instantiate the factory, call the 
appropriate factory method and return the result. There are 
thousands of such object/factory pairs in the API. Just trying to 
cut out a lot of boilerplate code, but it doesn't seem doable 
this way.


Making external types available to mixins

2018-11-17 Thread John Chapman via Digitalmars-d-learn
The following code doesn't compile because the generated type 
name needs to be available inside the mixin's scope, whereas it's 
actually in another module.


auto makeWith(string className, Args…)(auto ref Args args) {
  mixin("return makeWith!(I", className, "Factory)(args);"); // 
Fowarded to implementation of makeWith below

}

auto makeWith(T, Args…)(auto ref Args args) … // This is the 
implementation


The idea is that users could type (for example) 
makeWith!`Calendar`(…) instead of the longer 
makeWith!ICalendarFactory(…).


I tried mixing in an import statement with the help of 
std.traits.moduleName so that the I...Factory type would be 
available but again the compiler complains that it's undefined.


Has anyone had a similar need and come up with a solution?


Re: Accessing LPARAM param from SendMessage acts weird.

2018-11-04 Thread John Chapman via Digitalmars-d-learn

On Sunday, 4 November 2018 at 19:06:22 UTC, Mark Moorhen wrote:

Another Windows challenge:

I'm trying to get the title of the active window even if it is 
from an external application. This is what I've come up with so 
far:



import std.stdio;
import core.sys.windows.windows;

extern (Windows)

void main()
{
HWND foreground = GetForegroundWindow();
const(wchar) title;

int length = SendMessage(foreground, WM_GETTEXTLENGTH, 0, 0);
	SendMessage(foreground, WM_GETTEXT, length, 
LPARAM(title));			//LPARAM is a Long Pointer


writeln(length);
writeln(title);

}


Outputs :

27
  ´┐┐

So the lengt of the foreground windows title should be 27 chars 
long, but the title is only 3 chars (and kinda funny ones too:-(


Anyone ideas?


You need to allocate some memory to receive the string from 
WM_GETTEXT.


  auto length = SendMessage(foreground, WM_GETTEXTLENGTH, 0, 0);
  auto buffer = new wchar[length + 1]; // +1 for the trailing 
null character
  SendMessage(foreground, WM_GETTEXT, buffer.length, 
cast(LPARAM)buffer.ptr);

  auto title = cast(wstring)buffer[0 .. length];
  writeln(title);


Re: Private struct constructor

2018-10-04 Thread John Chapman via Digitalmars-d-learn

On Thursday, 4 October 2018 at 07:31:21 UTC, Ritchie wrote:

Any reason why this works?

https://run.dlang.io/is/TALlyw


"private" applies to the module, not the type. 
https://dlang.org/spec/attribute.html#visibility_attributes


Re: Use nested functions as callbacks with Windows API functions?

2018-10-02 Thread John Chapman via Digitalmars-d-learn

On Monday, 1 October 2018 at 20:27:43 UTC, spikespaz wrote:
Of course there is nothing wrong with defining each callback as 
a separate function, but then comes the issue of naming them. I 
also don't like the way it makes my code look.


I think the best you can do is something like this:

---
auto callback(T, string file = __FILE__, size_t line = 
__LINE__)(T handler) {

  import std.traits;

  __gshared T handler_;
  handler_ = handler;

  extern(Windows)
  ReturnType!T fn(Parameters!T args) {
synchronized return handler_(args);
  }

  return 
}

void main() {
  HWND[] list;
  EnumWindows((HWND hwnd, LPARAM lparam) {
list ~= hwnd;
return TRUE;
  }.callback(), 0);
  writeln(list);
}
---



Re: Convert output range to input range

2018-03-17 Thread John Chapman via Digitalmars-d-learn

On Saturday, 17 March 2018 at 17:16:40 UTC, David Nadlinger wrote:

On Friday, 16 March 2018 at 07:57:04 UTC, John Chapman wrote:
I need to write to a range created with outputRangeObject, 
then read from it. Is there a way to convert it to an input 
range?


Could you illustrate your problem a bit further?


I'm trying to replace the old std.streams in my app with ranges. 
I'm interfacing with a networking library to which I supply a 
callback that when invoked provides the requested data. I write 
that data to an output range, but later on I need to read that 
data from the range too - which of course you can't do.


So what I'm looking for is the range-based equivalent of a 
MemoryStream.




Convert output range to input range

2018-03-16 Thread John Chapman via Digitalmars-d-learn
I need to write to a range created with outputRangeObject, then 
read from it. Is there a way to convert it to an input range?


Re: How to proceed with learning to code Windows desktop applications?

2018-01-31 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 31 January 2018 at 11:52:20 UTC, rumbu wrote:
On Windows platform, WPF is the way to go right now. Once you 
accommodate yourself with XAML (descriptive language for 
designing windows and controls), you can step up from WPF to 
modern Windows apps (UWP). Unfortunately, none of these 
technologies are supported in D.


Just to say that it is actually possible to write modern Windows 
apps in D - I've done it. WinRT is just COM. Granted it's not as 
easy as using Microsoft's language projections, but it's doable 
if you really want to.


Re: Get aliased type

2018-01-02 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 2 January 2018 at 12:19:19 UTC, David Nadlinger wrote:
There is indeed no way to do this; as you say, aliases are just 
names for a particular reference to a symbol. Perhaps you don't 
actually need the names in your use case, though?


 — David


The idea was to distinguish between a BSTR (an alias for wchar* 
from core.sys.windows.wtypes used widely with COM) and wchar* 
itself, chiefly so that I could call the appropriate Windows SDK 
functions on them to convert them to and from D strings. Although 
BSTRs look like wchar*s to the end user they are not really 
interchangable - for example, calling SysFreeString on a regular 
wchar* will cause a crash.


According to the docs, a BSTR is prefixed with its length and 
ends in a null character, but I'm not sure if checking for the 
existence of those is going to be good enough.


Get aliased type

2018-01-02 Thread John Chapman via Digitalmars-d-learn
Because an alias of a type is just another name for the same 
thing you can't test if they're different. I wondered if there 
was a way to get the aliased name, perhaps via traits? (.stringof 
returns the original type.)


I can't use Typedef because I'm inspecting types from sources I 
don't control.


Re: std.file and non-English filename in Windows

2018-01-01 Thread John Chapman via Digitalmars-d-learn

On Sunday, 31 December 2017 at 18:21:29 UTC, Domain wrote:
In Windows, exists, rename, copy will report file not exists 
when you input non-English filename, such as Chinese 中文.txt


Works for me. I created a file with the name "中文.txt" and 
std.file.exists returned true.


Is your D source file saved in ASCII by any chance? Try saving it 
with a different encoding, such as UTF8.


Re: Calling a d-style-variadic-function from another

2017-12-30 Thread John Chapman via Digitalmars-d-learn

On Saturday, 30 December 2017 at 10:14:35 UTC, tipdbmp wrote:


// how can I adjust _argptr?
_argptr = ???


Try this:
  _argptr = *cast(va_list*)_argptr;



Re: Is variable void?

2017-11-25 Thread John Chapman via Digitalmars-d-learn
On Saturday, 25 November 2017 at 15:38:15 UTC, Adam D. Ruppe 
wrote:
nope. It'd be indistinguishable from the user just happening to 
initialize it to some random value.


Thanks. I'll got with .init instead.



Is variable void?

2017-11-25 Thread John Chapman via Digitalmars-d-learn
Is there any way of determining whether a variable has been 
initialized or not? For example, if something is declared like 
this:


  int x = void;

can I check if it's void before I use it, say, in a function it's 
been passed to?




Re: Whats the correct way to pass a D array type to a win32 api function wanting a buffer?

2017-07-13 Thread John Chapman via Digitalmars-d-learn

On Thursday, 13 July 2017 at 01:15:46 UTC, FoxyBrown wrote:

ENUM_SERVICE_STATUS_PROCESS[5000] services;
	auto res = SVC.EnumServicesStatusExA(schSCManager, 
SC_ENUM_TYPE.SC_ENUM_PROCESS_INFO, servicesType, 
SERVICE_STATE_ALL, cast(ubyte*)services.ptr, 
5000*ENUM_SERVICE_STATUS_PROCESS.sizeof, , 
, , cast(const(char)*)null);


You need to call EnumServicesStatusEx twice - the first time to 
get the required size of the buffer. See the docs for the 
lpServices parameter here 
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682640(v=vs.85).aspx


Then allocate a buffer using the returned dwBytesNeeded and call 
the function again with your buffer and its size.


Re: COM Expertise needed: COM Callbacks

2017-04-28 Thread John Chapman via Digitalmars-d-learn

On Thursday, 27 April 2017 at 20:20:23 UTC, Nierjerson wrote:


I think the main issue though, is that I really don't know what 
is going on when I invoke the PS function. It seems to call the 
server method that takes the interface and then the server does 
it's "magic"(which is calling my QueryInterface) but how the 
implemented QueryInterface is suppose to respond is beyond 
me... I've tried some based stuff but nothing seem to work. The 
good news is that it is doing something(calling QueryInterface) 
which means that the server is at work.


Any more ideas?  I think the issue currently is is the 
QueryInterface(it is simply not doing what it is suppose to). 
I'll probably have to look at some other implementations to see 
what is going on.


QueryInterface is COM's version of opCast. It asks if you support 
the interface represented by an IID (riid). If you don't, then 
you return E_NOINTERFACE. If you do, then you point the result 
(pvObject) to yourself and return S_OK. Here's a basic 
implementation:


extern(Windows)
HRESULT QueryInterface(IID* riid, void** pvObject) {
  if (pvObject is null) return E_POINTER;
  *pvObject = null;

  if (*riid == IID_IUnknown) *pvObject = 
cast(void*)cast(IUnknown)this;
  else if (*riid == IID_IDispatch) *pvObject = 
cast(void*)cast(IDispatch)this;

  // and so on for all interfaces we support

  if (*pvObject is null) return E_NOINTERFACE;
  (cast(IUnknown)this).AddRef();
  return S_OK;
}

AddRef/Release perform the COM object's reference counting, so 
you should implement them too.


However, I don't understand why your icRBCColor class both 
implements and encapsulates IDispatch - the generated version 
cRGBColor from Gen.d just encapsulates it. Why do you need to 
instantiate an instance of icRGBColor? Can't you just use the 
rgb1 object you got from the dd.RGB() getter, assign the colour 
values to its Red, Blue, Green properties as needed, then call 
the dd.RGB(rgb1) setter? Does that not work?


Re: COM Expertise needed: COM Callbacks

2017-04-27 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 26 April 2017 at 23:04:53 UTC, Nierjerson wrote:

On Wednesday, 26 April 2017 at 15:30:37 UTC, John Chapman wrote:

On Tuesday, 25 April 2017 at 18:39:56 UTC, Nierjerson wrote:

[...]


When you use DISPATCH_PROPERTYPUT you need to set cNamedArgs 
and rgdispidNamedArgs like so:


  int dispidNamed = DISPID_PROPERTYPUT;
  params.cNamedArgs = 1;
  params.rgdispidNamedArgs = 

You should also call AddRef on any COM objects you add to your 
paramVars array.



Did you try this? I tried and same issue. Are you sure the 
above is required? I'm not using any "named" args so not sure 
why it should matter?


From the documentation 
(https://msdn.microsoft.com/en-us/library/windows/desktop/ms221479(v=vs.85).aspx):


"When you use IDispatch::Invoke() with DISPATCH_PROPERTYPUT or 
DISPATCH_PROPERTYPUTREF, you have to specially initialize the 
cNamedArgs and rgdispidNamedArgs elements of your DISPPARAMS 
structure"


Thought it might help.



Re: COM Expertise needed: COM Callbacks

2017-04-26 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 25 April 2017 at 18:39:56 UTC, Nierjerson wrote:

void RGB(icRGBColor ic, cSolidColor s)
{
import main;
EXCEPINFO exception;
uint argErr = 0;
auto iidNULL = IID_NULL;
auto RT = new SafeVariantPtr();
VARIANT[1] paramVars;
	DISPPARAMS params = {rgvarg: paramVars.ptr, cArgs: 1, 
cNamedArgs: 0};

auto ID = s.COMMethodIDs[`RGB`];
	paramVars[0].punkVal = ic; paramVars[0].vt = 
VARENUM.VT_DISPATCH; scope(exit) VariantClear([0]);
	auto res = s.iDispatch.Invoke(cast(int)ID, , 0, 
DISPATCH_PROPERTYPUT, , cast(VARIANT*)RT, , 
);
	assert(res == S_OK, `Could not invoke COM Function 
cSolidColor.RGB. Error `~to!string(res, 16));


}


When you use DISPATCH_PROPERTYPUT you need to set cNamedArgs and 
rgdispidNamedArgs like so:


  int dispidNamed = DISPID_PROPERTYPUT;
  params.cNamedArgs = 1;
  params.rgdispidNamedArgs = 

You should also call AddRef on any COM objects you add to your 
paramVars array.


Re: opDispatch/template get this

2017-04-04 Thread John Chapman via Digitalmars-d-learn

On Monday, 3 April 2017 at 21:49:07 UTC, Inquie wrote:

I am using opDispatch to wrap function calls

Error: 'this' is only defined in non-static member functions, 
not opDispatch!"foo"


class X
{
auto localfoo() { return 3; }
template opDispatch(string name, Args...)
{
static if (name == `foo`) { alias opDispatch = () { 
return this.localfoo();

};
}


which doesn't work because of this

I tried

template opDispatch(string name, this _this, Args...)
{
	static if (name == `foo`) { alias opDispatch = () { return 
_this.localfoo(); };

}

but that doesn't work either ;/

I call it like

auto y = x.foo();

but foo isn't found


https://dpaste.dzfl.pl/bf31f535340f



class X
{
auto localfoo() { return 3; }
auto localfoo2(int x) { return x; }
template opDispatch(string name, Args...)
{
static if (name == `foo`)
{
alias opDispatch = () { return this.localfoo(); };
}
static if (name == `bar`)
{
			alias opDispatch = () { return this.localfoo2(); }; // need 
to be able to pass Args properly here

}
}
}

void main()
{
auto x = new X();
auto z = x.localfoo();
auto y = x.foo();
auto q = x.bar();
}


Make opDispatch a templated function and forward with 
__traits(getMember, this, "foo") or a mixin.


class X {

  auto localfoo() { return 3; }
  auto localfoo2(int x) { return x; }

  auto opDispatch(string name, Args...)(auto ref Args args) {
static if (name == "foo") return __traits(getMember, this, 
"localfoo")(args);
else static if (name == "bar") mixin("return 
localfoo2(args);");

  }

}


Re: COM2D Wrapper

2017-03-28 Thread John Chapman via Digitalmars-d-learn

On Monday, 27 March 2017 at 21:02:05 UTC, Nierjerson wrote:
Anyone can help get this working? I think the issue maybe that 
the interface pointer returned by the COM interface is "C-like" 
and doesn't match what D expects an interface to be. I get 
access violations when trying to call the functions on the 
returned interfaces. Not sure about this though.


I don't have Photoshop so I can't verify this, however I think 
Photoshop only declares dispinterfaces, meaning those methods 
aren't present in the vtable, so every method will have to be 
called using IDispatch.Invoke.


(I'm guessing IDL2D doesn't distinguish between dual and disp- 
interfaces and just emits any functions it sees.)


Re: Working Windows GUI library - no console Window

2015-11-06 Thread John Chapman via Digitalmars-d-learn

On Friday, 6 November 2015 at 15:52:10 UTC, johann wrote:

hi,
i like to use a window gui library and i think i found a 
working one.


https://github.com/FrankLIKE/dfl2  - works with x64

the problem is, that with DMD 2.069.0, VS2015 and visualD the 
trick of using "-L/SUBSYSTEM:windows,6.00 
-L/ENTRY:mainCRTStartup" does not suppress the console window 
anymore.


does anybody have a solution for that problem?
is anybody still working on that library?

johann


Same problem here. I had to remove the mainCRTStartup flag and 
use WinMain as my entry point.


Re: how to iterate on Array?

2015-06-27 Thread John Chapman via Digitalmars-d-learn

On Saturday, 27 June 2015 at 17:43:13 UTC, aki wrote:

I want to print the contents of Array!int

import std.stdio;
import std.container;

void pr(Array!int a) {
foreach(i, v; a[]) {
writeln(%4s: %s\n, i, v);
}
}

But when I compile it by DMD 2.062 on Windows
it says:

testArray.d(5): Error: cannot infer argument types
(line 5 is at foreach(i, v; a[]) { )

What's wrong? how can I iterate the array?

Thanks, aki.


size_t i;
foreach (v; a[])
  writeln(%s: %s, i++, v);


Re: Can't call GetWindowTextW - Error:undefined identifier

2015-06-17 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 17 June 2015 at 20:50:27 UTC, John Chapman wrote:

  wchar[MAX_PATH] buffer;
  int length = GetWindowTextW(GetForegroundWindow(), 
buffer.ptr, buffer.length);


Don't know why I used MAX_PATH there. You should probably 
dynamically allocate a buffer based on GetWindowTextLengthW.


  extern(Windows)
  int GetWindowTextLengthW(HWND hWnd);

Putting it all together:

  import core.stdc.stdlib : malloc, free;
  import std.utf;

  HWND hwnd = GetForegroundWindow();
  int length = GetWindowTextLengthW(hwnd);
  if (length  0) {
auto buffer = cast(wchar*)malloc((length + 1) * wchar.sizeof);
scope(exit) free(buffer);

length = GetWindowTextW(hwnd, buffer, length);
if (length  0)
  auto title = buffer[0 .. length].toUTF8();
  }


Re: Can't call GetWindowTextW - Error:undefined identifier

2015-06-17 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 17 June 2015 at 21:00:55 UTC, Dan wrote:

thank you John it worked :)

do I always need do the same for all windows API?


For most Win32 API functions, yes. Although there are some more 
complete headers on Github (for example, 
https://github.com/rikkimax/WindowsAPI).


Re: Can't call GetWindowTextW - Error:undefined identifier

2015-06-17 Thread John Chapman via Digitalmars-d-learn

On Wednesday, 17 June 2015 at 20:40:02 UTC, Dan wrote:

I'm new to Dlang and I have no Idea whats wrong with this code!

wchar[260] buffer;
HWND hWindow = GetForegroundWindow();
GetWindowTextW(hWindow, buffer, sizeof(title)); -- Problem here


The compiler is complaining it can't find an identifier named 
GetWindowTextW, so you'll have to declare it yourself.


Try this:

  extern(Windows)
  int GetWindowTextW(HWND hWnd, LPWSTR lpString, int nMaxCount);

And call it like so:

  wchar[MAX_PATH] buffer;
  int length = GetWindowTextW(GetForegroundWindow(), buffer.ptr, 
buffer.length);


Re: Calling a cpp function from d

2015-06-17 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 16 June 2015 at 12:42:16 UTC, C2D wrote:

On Tuesday, 16 June 2015 at 12:31:23 UTC, John Chapman wrote:

On Tuesday, 16 June 2015 at 12:26:45 UTC, C2D wrote:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, cache.ptr);


That should be:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, buf.ptr);


Thanks, but I'm still getting the same error -


Use SHGetFolderPathW.


Re: Calling a cpp function from d

2015-06-17 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 16 June 2015 at 12:42:16 UTC, C2D wrote:

On Tuesday, 16 June 2015 at 12:31:23 UTC, John Chapman wrote:

On Tuesday, 16 June 2015 at 12:26:45 UTC, C2D wrote:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, cache.ptr);


That should be:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, buf.ptr);


Thanks, but I'm still getting the same error -


Here's a working version:

import core.sys.windows.windows;

extern(Windows)
HRESULT SHGetFolderPathW(HWND hwndOwner, int nFolder, HANDLE 
hToken, DWORD dwFlags, LPWSTR pszPath);


string getFolderPath(int folder) {
  import core.stdc.wchar_ : wcslen;
  import std.utf : toUTF8;

  wchar[MAX_PATH] buffer;
  if (SHGetFolderPathW(null, folder, null, 0, buffer.ptr) = 0)
return buffer[0 .. wcslen(buffer.ptr)].toUTF8();
  return null;
}

void main() {
  writeln(getFolderPath(0x23));
}


Re: Calling a cpp function from d

2015-06-16 Thread John Chapman via Digitalmars-d-learn

On Tuesday, 16 June 2015 at 12:26:45 UTC, C2D wrote:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, cache.ptr);


That should be:

BOOL result = SHGetFolderPath(null, 0x23, null, 0, buf.ptr);


Re: windows wininet library

2015-02-01 Thread John Chapman via Digitalmars-d-learn

On Sunday, 1 February 2015 at 08:37:23 UTC, ketmar wrote:


seems that my idea of using D to write a simple windows utility 
was very
wrong. ok, another attempt to use D for our windows 
developement has
failed. i'm in no way can sell manual .def creation to our 
team -- they
will make fun of me, showing how their Visual C can compile 
this code

without any troubles and external utilities...


It's easier to run coffimplib on the lib files from the Windows 
SDK.


Re: sign oauth request

2014-09-25 Thread John Chapman via Digitalmars-d-learn
there is no HMAC-SHA1 algorithm in phobos library... should I 
implement it from scratch?


http://dlang.org/phobos/std_digest_sha.html#SHA1