Do you know, if it's possible to start a software on a specific monitor? And how this can be done?
I have a node.js server on my computer (windows 10) and I need to start some external software (I can't change code in that external software, because I only have the exe-file). The final application should work on a setup with a real monitor and a second fake monitor. On the first monitor is a browser window in full screen. There is a start and stop button (they work already) to start and stop the external software. On the second monitor (not visible) should start the external software.
If everything works this way, I can connect per remote on that computer and look at the second screen. There I can use the external software. And on the Monitor (1) of that computer is always only the browser window visible.
To test I use notepad.exe as the external software.
If I click start, the software opens on my main monitor (1) but it should start on the second monitor.
Thanks for your help.
It looks like, it's not possible to do that directly. But if you start from node.js a little helper program it's not that difficult. You can start it with execFile() look at: nodejs docs
I made a little C# console application with following functions:
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
public static extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "ShowWindow")]
public static extern bool ShowWindow(IntPtr hWnd, int cmdShow);
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool MoveWindow(IntPtr hWnd, int x, int y, int nWidth, int nHeight, bool bRepaint);
Then I iterated through System.Windows.Forms.Screen.AllScreens and started with Process my executable. From Process I got the MainWindowHandle and with that, it's possible to set the window on the screen you want.
static void Main(string[] args)
{
if (args.Length == 1 && args[0].Equals("h"))
{
Console.Out.WriteLine("Command: [displayName] [executable] [arguments for executable]");
return;
}
if (args.Length < 2)
{
Console.Out.WriteLine("arguments not correct. Should be: [displayName] [executable1] [arguments for executable]");
return;
}
foreach (var screen in Screen.AllScreens)
{
Console.Out.WriteLine(screen.DeviceName);
if (screen.DeviceName.Equals(args[0]))
{
var process = new Process();
process.StartInfo.FileName = args[1];
string[] arguments = args.Skip(2) as string[];
if (arguments != null) process.StartInfo.Arguments = string.Join(" ", arguments);
process.Start();
var hwnd = process.MainWindowHandle;
Console.Out.WriteLine("while get process.MainWindowHandle");
while (!process.HasExited)
{
process.Refresh();
if (process.MainWindowHandle.ToInt32() != 0)
{
hwnd = process.MainWindowHandle;
break;
}
}
Console.Out.WriteLine("windowHandle: " + hwnd);
MoveWindow(hwnd, screen.WorkingArea.X, screen.WorkingArea.Y, screen.WorkingArea.Width, screen.WorkingArea.Height, true);
ShowWindow(hwnd, SwMaximize);
SetForegroundWindow(hwnd);
// Waits here for the process to exit.
process.WaitForExit();
return;
}
}
Console.Out.WriteLine("screen not found: " + args[0]);
}
}
Related
How would we go about changing the system time on a linux system programatically using QT widget application ?
You can use dbus to interface with timedated daemon https://www.freedesktop.org/wiki/Software/systemd/timedated/
to set time and date.
Qt provides a way to generate interface code from xml
http://doc.qt.io/qt-5/qdbusxml2cpp.html. You can get xml by introspection.
I don't like generated code formatting so I wrote interface code myself
h:
#ifndef TIMEDATE1SERVICE_H
#define TIMEDATE1SERVICE_H
#include <QObject>
#include <QString>
#include <QVariant>
#include <QtDBus>
class Timedate1Interface: public QDBusAbstractInterface
{
Q_OBJECT
Q_PROPERTY(bool CanNTP READ CanNTP)
Q_PROPERTY(bool LocalRTC READ LocalRTC)
Q_PROPERTY(bool NTP READ NTP)
Q_PROPERTY(bool NTPSynchronized READ NTPSynchronized)
Q_PROPERTY(qulonglong RTCTimeUSec READ RTCTimeUSec)
Q_PROPERTY(qulonglong TimeUSec READ TimeUSec)
Q_PROPERTY(QString Timezone READ Timezone)
public:
explicit Timedate1Interface(QObject *parent = nullptr);
bool CanNTP() const;
bool LocalRTC() const;
bool NTP() const;
bool NTPSynchronized() const;
qulonglong RTCTimeUSec() const;
qulonglong TimeUSec() const;
QString Timezone() const;
void SetLocalRTC(bool localRTC, bool fixSystem, bool userInteraction);
void SetNTP(bool useNTP, bool userInteraction);
void SetTime(qlonglong usecUTC, bool relative, bool userInteraction);
void SetTimezone(const QString &timezone, bool userInteraction);
};
#endif // TIMEDATE1SERVICE_H
cpp:
#include "timedate1service.h"
Timedate1Interface::Timedate1Interface(QObject *parent)
: QDBusAbstractInterface("org.freedesktop.timedate1", "/org/freedesktop/timedate1",
"org.freedesktop.timedate1", QDBusConnection::systemBus(), parent)
{
}
bool Timedate1Interface::CanNTP() const
{
return qvariant_cast<bool>(property("CanNTP"));
}
bool Timedate1Interface::LocalRTC() const
{
return qvariant_cast<bool>(property("LocalRTC"));
}
bool Timedate1Interface::NTP() const
{
return qvariant_cast<bool>(property("NTP"));
}
bool Timedate1Interface::NTPSynchronized() const
{
return qvariant_cast<bool>(property("NTPSynchronized"));
}
qulonglong Timedate1Interface::RTCTimeUSec() const
{
return qvariant_cast<qulonglong>(property("RTCTimeUSec"));
}
qulonglong Timedate1Interface::TimeUSec() const
{
return qvariant_cast<qulonglong>(property("TimeUSec"));
}
QString Timedate1Interface::Timezone() const
{
return qvariant_cast<QString>(property("Timezone"));
}
void Timedate1Interface::SetLocalRTC(bool localRTC, bool fixSystem, bool userInteraction)
{
call("SetLocalRTC", localRTC, fixSystem, userInteraction);
}
void Timedate1Interface::SetNTP(bool useNTP, bool userInteraction)
{
call("SetNTP", useNTP, userInteraction);
}
void Timedate1Interface::SetTime(qlonglong usecUTC, bool relative, bool userInteraction)
{
call("SetTime", usecUTC, relative , userInteraction);
}
void Timedate1Interface::SetTimezone(const QString &timezone, bool userInteraction)
{
call("SetTimezone", timezone, userInteraction);
}
You cannot do that in pure Qt. You need to use Linux (or POSIX) specific things.
And you probably should not do that, but better yet configure your entire system to use NTP (e.g. by running some NTP client...). Most Linux distributions have that already.
If you really want to set the system time (but you should not do that directly from a Qt application, since Qt applications should not run as root, but see this), read time(7) then adjtimex(2) & settimeofday(2)
You need to be root for that, so you should not do that from a Qt application. You might use setuid techniques to run some specific command or program as root. Setuid is tricky (see credentials(7), execve(2), setreuid(2)...), could open a giant security hole if misused (and making mistakes is easy), so read something about Linux programming, e.g. the old ALP.
So if you insist doing that (and it is probably wrong), write a tiny specific program in C for that and make it setuid and run that setuid-program from your Qt application (e.g. using QProcess).
I found a simple solution. As my system is very minimalist i dont want to use things like dbus. As a root or sudoer this can be execute (fairly self explainatory )-
QString string = dateTime.toString("\"yyyy-MM-dd hh:mm\"");
QString dateTimeString ("date -s ");
dateTimeString.append(string);
int systemDateTimeStatus= system(dateTimeString.toStdString().c_str());
if (systemDateTimeStatus == -1)
{
qDebug() << "Failed to change date time";
}
int systemHwClockStatus = system("/sbin/hwclock -w");
if (systemHwClockStatus == -1 )
{
qDebug() << "Failed to sync hardware clock";
}
Platform: Qt 4.8.2 (built from source using MinGW x64), Win 7
I'm using QRunnable to separate long running tasks from main GUI thread, and I sometimes experience random crash/strange behavior with no traceable errors. Please help to provide suggestions on what/how to debug. Thanks
Runner class: multi-inherit for signal/slot connection to main window
class MyRunner : public QObject, public QRunnable
{
Q_OBJECT
Q_SIGNALS:
void feedbackLog(QString text);
void finished();
public:
explicit MyRunner(/* some args */) { /* some initialization */ }
void run() {
stopped_ = false;
for (int run = 0; run < SOME_COUNT; run++) {
Q_EMIT feedbackLog("Resetting everything ...");
if (stopped_) return;
/* start the daily interaction until the epidemic is over */
do
{
if (stopped_) return;
lengthySubTaskA();
if (stopped_) return;
lengthySubTaskB();
if (stopped_) return;
lengthySubTaskC();
}
while (conditionNotReached());
} // end: for(run)
stopped_ = true;
Q_EMIT finished();
}
bool isStopped() { return stopped_; }
public Q_SLOTS:
void stop() {
Q_EMIT feedbackLog("Cancel ...");
stopped_ = true;
}
private:
bool stopped_;
/** other class members follow */
};
MainWindow segment
void MainWindow::callMyRunnable() {
runner_ = new MyRunner(/* args */); // runner_ is class member */
runner_->setAutoDelete(true); // (a)
progress_dialog_ = new QProgressDialog("Running", "Cancel", 0, 0, this);
progress_dialog_->setAttribute(Qt::WA_DeleteOnClose);
connect(runner_, SIGNAL(feedbackLog(QString)), SLOT(logMessage(QString)));
connect(runner_, SIGNAL(finished()), SLOT(endLengthyJob()));
connect(runner_, SIGNAL(finished()), progress_dialog_, SLOT(close()));
connect(progress_dialog_, SIGNAL(canceled()), runner_, SLOT(stop()));
connect(progress_dialog_, SIGNAL(canceled()), SLOT(endLengthyJob()));
QThreadPool::globalInstance()->start(runner_);
progress_dialog_->show();
/* flu_runner_->deleteLater(); */ // (b)
}
void MainWindow::closeEvent(QCloseEvent *e) {
if (runner_ && !runner_->isStopped()) runner_->stop(); // (c)
if (QThreadPool::globalInstance()->activeThreadCount())
{
/* display a dialog to notify user about shutdown */
Dialog::WaitDialog dlg(5 * 1000);
dlg.exec();
}
event->accept();
} // end_event(MainWindow::closeEvent)
1) If I disable autodelete at (a), should I add statement (b) to prevent leaking? Or any better way to handle the leaking?
2) Sometimes, when the Runnable task completed, I cannot close the app normally (neither [x] button nor Alt-F4 work), and I have to kill the app from within QtCreator (I'm debugging, right?). What would be possible cause to this?
[Edit]: 3) For un-closable mainwindow, sometimes it happens after I cancelled the task handled by MyRunner class, will this be a possible cause?
[Edit]: I added qDebug() statement around (c), and found that it stop at (c) and refuse to proceed to display the waiting dialog in case if the [x] button is not responding.
Thanks.
The problem is solved by changing the 'close-strategy' of the mainwindow: remove 'auto-killing' and force user to wait for spawned thread. Variables runner_ and progress_dialog_ are now localized to the function callMyRunnable()
Platform: Windows 7 Professional 64 bit
Compiler: VS2010 Express
Boost: Version 1.49
Plugin System: OBSE 20 (for the Oblivion game by Bethesda)
I have a class based upon the async udp examples. I run the io service itself as a thread. Here is the code for the class:
// udp buffer queues
extern concurrent_queue<udp_packet> udp_input_queue; // input from external processes
extern concurrent_queue<udp_packet> udp_output_queue; // output to external processes
using boost::asio::ip::udp;
class udp_server
{
public:
udp_server(boost::asio::io_service& io_service, short port)
: io_service_(io_service),
socket_(io_service_, udp::endpoint(boost::asio::ip::address_v4::from_string(current_address), port))//, // udp::v4()
{
// start udp receive
socket_.async_receive_from(
boost::asio::buffer(recv_buf), sender_endpoint_,
boost::bind(&udp_server::handle_receive_from, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
send_timer_ = NULL;
}
~udp_server(){
io_service_.stop();
if(send_timer_){
send_timer_->cancel();
delete send_timer_;
}
}
void start(){
// start send timer
send_timer_ = new boost::asio::deadline_timer(io_service_, boost::posix_time::milliseconds(500));
send_timer_restart();
}
void handle_send_to(const boost::system::error_code& error, size_t bytes_recvd);
void handle_receive_from(const boost::system::error_code& error, size_t bytes_recvd);
//void handle_send_timer(const boost::system::error_code& error);
void handle_send_timer();
void send_timer_restart();
void stop()
{
io_service_.stop();
}
private:
boost::asio::io_service& io_service_;
udp::socket socket_;
udp::endpoint sender_endpoint_;
std::vector<udp::endpoint> clientList;
//std::auto_ptr<boost::asio::io_service::work> busy_work;
udp_buffer recv_buf;
boost::asio::deadline_timer* send_timer_;
};
Now I instantiate the class and thread like this:
udp_server *udp_server_ptr=NULL;
boost::asio::deadline_timer* dlineTimer=NULL;
static void PluginInit_PostLoadCallback()
{
_MESSAGE("NetworkPipe: PluginInit_PostLoadCallback called");
if(!g_Interface->isEditor)
{
_MESSAGE("NetworkPipe: Starting UDP");
udp_server_ptr = new udp_server(io_service, current_port);
//dlineTimer = new boost::asio::deadline_timer(io_service);
udp_thread = new boost::thread(boost::bind(&boost::asio::io_service::run, &io_service));
//
_MESSAGE("NetworkPipe: UDP Started");
NetworkPipeEnable = true;
}
else
{
_MESSAGE("NetworkPipe: Running in editor, not starting UDP");
}
}
Now notice that dlineTimer is commented out above. If I enable that it ceases to function. The only way I can get the dlineTimer to function with this io service is to create it during the udp_server::handle_receive_from call. I think this is because it is running inside the other thread. So for some reason the deadline_timer object does not like being created outside the thread it needs to run inside.
Now, in order to communicate to the main thread I use concurrent_queue objects. So these allow me to send messages in and out of the thread pretty simply. I could theoretically run the dlineTimer inside its own thread and use the output queue to manage its activity. However, I like the simplicity of having is in the same thread as the udp_server. For instance the udp_server object keeps track of clients in a vector. When the deadline_timer expires I cycle through the known clients and send them messages. Then I restart the timer. This makes my response independent of the udp packets that are sent to the server. So when packets arrive they are put on a queue for another part of the process. Then later data is placed on the output queue and the deadline_timer processes those responses and sends them to the appropriate clients.
So my main question is:
How do I more cleanly create the deadline_timer object using the same thread and same io_service as the udp_server object?
Okay, I was thinking about this really stupidly.
First the deadline_timer needs to be completely inside the thread I want it to time in. That means it needs to be created inside the thread.
Second I need to define the function called in the thread loop and not set it to the io_service::run function. So I made it the udp_server::start function. Inside the start call I create my deadline_timer.
So here is the class:
class udp_server
{
public:
udp_server(boost::asio::io_service& io_service, short port)
: io_service_(io_service),
socket_(io_service_, udp::endpoint(boost::asio::ip::address_v4::from_string(current_address), port))//, // udp::v4()
{
// start udp receive
socket_.async_receive_from(
boost::asio::buffer(recv_buf), sender_endpoint_,
boost::bind(&udp_server::handle_receive_from, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
send_timer_ = NULL;
}
~udp_server(){
io_service_.stop();
if(send_timer_){
send_timer_->cancel();
delete send_timer_;
}
}
void start();
void startSendTimer();
void handle_send_to(const boost::system::error_code& error, size_t bytes_recvd);
void handle_receive_from(const boost::system::error_code& error, size_t bytes_recvd);
void handle_send_timer();
void send_timer_restart();
void stop()
{
io_service_.stop();
}
private:
boost::asio::io_service& io_service_;
udp::socket socket_;
udp::endpoint sender_endpoint_;
std::vector<udp::endpoint> clientList;
udp_buffer recv_buf;
boost::asio::deadline_timer* send_timer_;
};
Here are the relevant functions:
void udp_server::start(){
// startup timer
startSendTimer();
// run ioservice
io_service_.run();
}
void udp_server::startSendTimer(){
// start send timer
if(!send_timer_)
send_timer_ = new boost::asio::deadline_timer(io_service_, boost::posix_time::milliseconds(500));
send_timer_restart();
}
void udp_server::send_timer_restart(){
if(send_timer_){
// restart send timer
send_timer_->expires_from_now(boost::posix_time::milliseconds(500));
send_timer_->async_wait(boost::bind(&udp_server::handle_send_timer, this));
}
}
void udp_server::handle_send_timer(){
for(std::vector<udp::endpoint>::iterator itr = clientList.begin(); itr != clientList.end(); ++itr){
socket_.async_send_to(
boost::asio::buffer("heart beat", strlen("heart beat")), *itr,
boost::bind(&udp_server::handle_send_to, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
send_timer_restart();
}
So I was thinking about this all wrong in the first place. I need to define my starting point of where the thread begins execution. The I can create the objects that need to reside in that thread inside the thread.
The udp_server is now started like this:
static void PluginInit_PostLoadCallback()
{
_MESSAGE("NetworkPipe: PluginInit_PostLoadCallback called");
if(!g_Interface->isEditor)
{
_MESSAGE("NetworkPipe: Starting UDP");
udp_server_ptr = new udp_server(io_service, current_port);
udp_thread = new boost::thread(boost::bind(&udp_server::start, udp_server_ptr));
_MESSAGE("NetworkPipe: UDP Started");
NetworkPipeEnable = true;
}
else
{
_MESSAGE("NetworkPipe: Running in editor, not starting UDP");
}
}
The deadline_timer creation occurs within the udp_thread now. Creating the deadline_timer object in the main thread would cause the program to fail to load properly.
I have previously used MiniZip (zlib wrapper) to unzip archives. MiniZip cannot be used for Metro applications as it uses deprecated APIs in "iowin32.c" -- CreateFile() and SetFilePointer().
I thought that would be an easy fix and created "iowinrt.c" with CreateFile() and SetFilePointer() replaced with CreateFile2() and SetFilePointerEx(). While this way I obtained a version of MiniZip that uses only approved Win8 APIs, it still turned out to be useless -- I forgot about sandboxing. If I pick a file using FileOpenPicker() and pass its path to my modified MiniZip I still cannot open it -- CreateFile2() will fail with "Access is denied." message.
So it appears that old C API for file access if now mostly useless; it is my understanding that in order to fix this I would need to reimplement my "iowinrt" in C++/CX using the new async file access. Are there any other options? I think I saw somewhere that WinRT does have compress/uncompress functionality but that it only works on individual files, not archives.
Additional requirements it that I need this to work in memory.
For a moment I thought I had a solution via .NET Framework 4.5:
I found this piece of info about how to create .NET classes that can be used from C++/CX:
http://social.msdn.microsoft.com/Forums/en-US/winappswithnativecode/thread/3ff383d0-0c9f-4a30-8987-ff2b23957f01
.NET Framework 4.5 contains ZipArchive and ZipArchiveEntry classes in System.IO.Compression:
http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive%28v=vs.110%29.aspx#Y0
http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchiveentry%28v=vs.110%29.aspx#Y0
I thought I could create C# Metro Class Library with WinMD Output type exposing ZipArchive and ZipArchiveEntry then use that in my C++/CX project. However, even if it worked it would not work in-memory; it appears that ZipArchive and ZipArchiveEntry work only with files.
Got reading from archive working. Explanation and code below but really just a hack at this point, to see if it's possible at all. I just kept modifying things until I got something working; this is just an example of what works and by no means a production quality code (it's not re-entrant for start). There are undoubtedly many things that are bad/unnecessary/wtf so feel free to use comments to help with clean up.
As mentioned previously, it is no longer enough to pass path to the library -- unless file is in one of KnownFolders (documents, home, media, music, pictures, removable or videos) you end up with "access is denied" message. Instead, library must be able to accept StorageFile^, as returned from FileOpenPicker. At least I haven't found any other way to do it, maybe someone knows better?
MiniZip provides Windows filesystem access layer for zlib via iowin32.h/.c. This still works in desktop mode for old-style apps, but does not work for Metro apps as it uses deprecated APIs and relies on paths. To get MiniZip going on Windows 8, a complete rewrite of iowin32 is required.
To get things working again, first thing was to find a way to pass StorageFile^ all the way down to iowinrt (Windows 8 replacement for iowin32). Fortunately, that was not a problem as MiniZip provides two styles of open file functions -- ones that accept pointer to char, and the others accepting pointer to void. Since ^ is still just a pointer, casting StorageFile^ to void* and than back to StorageFile^ works fine.
Now that I was able to pass StorageFile^ to my new iowinrt, the next problem was how to make new async C++ file access API work with Zlib. In order to support very old C compilers, Zlib is written with old K&R style C. VisualStudio compiler will refuse to compile this as C++, it has to be compiled as C, and new iowinrt must be compiled as C++ of course -- keep that in mind when creating your project. Other things to note about VS project is that I did it as Visual C++ Windows Metro style Static Library although DLL should also work but then you must also define macro to export MiniZip API (I haven't tried this, don't know which macro you have to use). I think I also had to set "Consume Windows Runtime Extension" (/ZW), set "Not Using Precompiled Headers" and add _CRT_SECURE_NO_WARNINGS and _CRT_NONSTDC_NO_WARNINGS to Preprocessor Definitions.
As for iowinrt itself, I've split it in two files. One holds two sealed ref classes -- reader and writer objects; they accept StorageFile^. Reader implements Read, Tell, SeekFromBeginning, SeekFromCurrent and SeekFromEnd (the reason for 3 Seek methods is because ref sealed classes have to stick with RT types and that apparently excludes enums so I just took the easy route). Writer implements just Write at the moment, haven't used it yet.
This is FileReader code:
#include "pch.h"
#include "FileAccess.h" // FileReader and FileWriter
using namespace Concurrency;
using namespace Windows::Security::Cryptography;
using namespace CFileAccess;
FileReader::FileReader(StorageFile^ archive)
{
if (nullptr != archive)
{
create_task(archive->OpenReadAsync()).then([this](IRandomAccessStreamWithContentType^ archiveStream)
{
if (nullptr != archiveStream)
{
_readStream = archiveStream;
}
}).wait();
}
} // end of constructor
int32 FileReader::Read(WriteOnlyArray<byte>^ fileData)
{
int32 bytesRead = 0;
if ((nullptr != _readStream) && (fileData->Length > 0))
{
try
{
auto inputStreamReader = ref new DataReader(_readStream);
create_task(inputStreamReader->LoadAsync(fileData->Length)).then([&](task<unsigned int> dataRead)
{
try
{
bytesRead = dataRead.get();
if (bytesRead)
{
inputStreamReader->ReadBytes(fileData);
}
}
catch (Exception^ e)
{
bytesRead = -1;
}
inputStreamReader->DetachStream();
}).wait();
}
catch (Exception^ e)
{
bytesRead = -1;
}
}
return (bytesRead);
} // end of method Read()
int64 FileReader::Tell(void)
{
int64 ret = -1;
if (nullptr != _readStream)
{
ret = _readStream->Position;
}
return (ret);
} // end of method Tell()
int64 FileReader::SeekFromBeginning(uint64 offset)
{
int64 ret = -1;
if ((nullptr != _readStream) && (offset < _readStream->Size))
{
_readStream->Seek(offset);
ret = 0;
}
return (ret);
} // end of method SeekFromBeginning()
int64 FileReader::SeekFromCurrent(uint64 offset)
{
int64 ret = -1;
if ((nullptr != _readStream) && ((_readStream->Position + offset) < _readStream->Size))
{
_readStream->Seek(_readStream->Position + offset);
ret = 0;
}
return (ret);
} // end of method SeekFromCurrent()
int64 FileReader::SeekFromEnd(uint64 offset)
{
int64 ret = -1;
if ((nullptr != _readStream) && ((_readStream->Size - offset) >= 0))
{
_readStream->Seek(_readStream->Size - offset);
ret = 0;
}
return (ret);
} // end of method SeekFromEnd()
iowinrt sits between MiniZip and FileReader (and FileWriter). It's too long to give everything here but this should be sufficient to reconstruct the rest since it's mostly just more of the same with different function names, plus a bunch of fill_winRT_filefuncxxx() which are obvious:
#include "zlib.h"
#include "ioapi.h"
#include "iowinrt.h"
#include "FileAccess.h"
using namespace Windows::Security::Cryptography;
using namespace Platform;
using namespace CFileAccess;
static FileReader^ g_fileReader = nullptr;
static FileWriter^ g_fileWriter = nullptr;
static StorageFile^ g_storageFile = nullptr;
[...]
static voidpf winRT_translate_open_mode(int mode)
{
if (nullptr != g_storageFile)
{
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
{
g_fileWriter = nullptr;
g_fileReader = ref new FileReader(g_storageFile);
}
else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
{
g_fileReader = nullptr;
g_fileWriter = ref new FileWriter(g_storageFile);
}
else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
{
g_fileReader = nullptr;
g_fileWriter = ref new FileWriter(g_storageFile);
}
}
return (nullptr != g_fileReader ? reinterpret_cast<voidpf>(g_fileReader) : reinterpret_cast<voidpf>(g_fileWriter));
}
voidpf ZCALLBACK winRT_open64_file_func (voidpf opaque,const void* storageFile,int mode)
{
g_storageFile = reinterpret_cast<StorageFile^>(const_cast<void*>(storageFile));
return (winRT_translate_open_mode(mode));
}
[...]
Long ZCALLBACK winRT_read_file_func (voidpf opaque, voidpf stream, void* buf,uLong size)
{
uLong bytesRead = 0;
if (nullptr != g_fileReader)
{
auto fileData = ref new Platform::Array<byte>(size);
bytesRead = g_fileReader->Read(fileData);
memcpy(buf, fileData->Data, fileData->Length);
}
return (bytesRead);
}
uLong ZCALLBACK winRT_write_file_func (voidpf opaque,voidpf stream,const void* buf,uLong size)
{
uLong bytesWritten = 0;
if (nullptr != g_fileWriter)
{
auto bytes = ref new Array<uint8>(reinterpret_cast<uint8*>(const_cast<void*>(buf)), size);
IBuffer ^writeBuffer = CryptographicBuffer::CreateFromByteArray(bytes);
bytesWritten = g_fileWriter->Write(writeBuffer);
}
return (bytesWritten);
}
long ZCALLBACK winRT_tell_file_func (voidpf opaque,voidpf stream)
{
long long ret = 0;
if (nullptr != g_fileReader)
{
ret = g_fileReader->Tell();
}
return (static_cast<long>(ret));
}
ZPOS64_T ZCALLBACK winRT_tell64_file_func (voidpf opaque, voidpf stream)
{
ZPOS64_T ret = 0;
if (nullptr != g_fileReader)
{
ret = g_fileReader->Tell();
}
return (ret);
}
[...]
long ZCALLBACK winRT_seek64_file_func (voidpf opaque, voidpf stream,ZPOS64_T offset,int origin)
{
long long ret = -1;
if (nullptr != g_fileReader)
{
switch (origin)
{
case ZLIB_FILEFUNC_SEEK_CUR :
ret = g_fileReader->SeekFromCurrent(offset);
break;
case ZLIB_FILEFUNC_SEEK_END :
ret = g_fileReader->SeekFromEnd(offset);
break;
case ZLIB_FILEFUNC_SEEK_SET :
ret = g_fileReader->SeekFromBeginning(offset);
break;
default:
// should never happen!
ret = -1;
break;
}
}
return (static_cast<long>(ret));
}
int ZCALLBACK winRT_close_file_func (voidpf opaque, voidpf stream)
{
g_fileWriter = nullptr;
g_fileReader = nullptr;
return (0);
}
int ZCALLBACK winRT_error_file_func (voidpf opaque,voidpf stream)
{
/// #todo Get errors from FileAccess
return (0);
}
This is enough to get MiniZip going (at least for reading) but you have to take care how you call MiniZip functions -- since Metro is all about async and blocking UI thread will end up with exception, you must wrap access in tasks:
FileOpenPicker^ openPicker = ref new FileOpenPicker();
openPicker->ViewMode = PickerViewMode::List;
openPicker->SuggestedStartLocation = PickerLocationId::ComputerFolder;
openPicker->FileTypeFilter->Append(".zip");
task<IVectorView<StorageFile^>^>(openPicker->PickMultipleFilesAsync()).then([this](IVectorView<StorageFile^>^ files)
{
if (files->Size > 0)
{
std::for_each(begin(files), end(files), [this](StorageFile ^file)
{ // open selected zip archives
create_task([this, file]()
{
OpenArchive(file);
[...]
});
});
}
else
{
rootPage->NotifyUserBackgroundThread("No files were returned.", NotifyType::ErrorMessage);
}
});
[...]
bool OpenArchive(StorageFile^ archive)
{
bool isArchiveOpened = false;
if (nullptr != archive)
{ // open ZIP archive
zlib_filefunc64_def ffunc;
fill_winRT_filefunc64(&ffunc);
unzFile archiveObject = NULL;
create_task([this, &ffunc, archive]()
{
archiveObject = unzOpen2_64(reinterpret_cast<const void*>(archive), &ffunc);
}).wait();
if (NULL != archiveObject)
{
[...]
Does anyone know the code or have ideas on how to kick off an .exe using Visual C++ 2005?
The environment the dll is on if Windows Mobile. The C# to do this using P/Invoke is
[DllImport("coredll.Dll")]
private static extern int CreateProcess(string strImageName, string strCmdLine, IntPtr pProcessAttributes, IntPtr pThreadAttributes , int bInheritsHandle, int dwCreationFlags, IntPtr pEnvironment, IntPtr pCurrentDir, Byte[] bArray, ProcessInfo oProc);
c# Code to start .exe
CreateProcess("\\Program Files\\myprogram\\myprogram.exe.exe", "", IntPtr.Zero, IntPtr.Zero, 0, 0, IntPtr.Zero, IntPtr.Zero, new Byte[128], pi);
The reason I need it in C++ is because I am forced to use a native dll to carry out pre and post intit checks etc when running a custom cab installer.
Your thoughts are much appreciated.
Tony
PROCESS_INFORMATION ProcessInfo = { 0 };
if (CreateProcess(ImagePath,
NULL,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
NULL,
&ProcessInfo))
{
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
}
else
{
return GetLastError();
}
Try this:
BOOL RunExe(CString strFile)
{
WIN32_FIND_DATA fd;
HANDLE hFind;
BOOL bFind;
hFind = FindFirstFile(strFile, &fd);
bFind = (hFind != INVALID_HANDLE_VALUE);
if(bFind)
{
if(!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
SHELLEXECUTEINFO info;
ZeroMemory(&info, sizeof(info));
info.cbSize = sizeof(info);
info.fMask = SEE_MASK_NOCLOSEPROCESS;
info.hwnd = 0;
info.lpVerb = _T("open");
info.lpFile = strFile;
info.lpParameters = NULL;
info.lpDirectory = NULL;
info.nShow = SW_SHOW;
info.hInstApp = NULL;
ShellExecuteEx(&info);
}
else
bFind = FALSE;
}
FindClose(hFind);
return bFind;
}
If you mean running an exe on the device, then no visual studio can't do it directly. You need to setup a custom build step or pre/post build steps to run a application that will do it for you. You can use the WM5 SDK code example prun (or create your own). PRun uses RAPI to run the application on the device, so the device needs to be connected through ActiveSync for this to work.
If you are trying to make stuff "automatically" happen on the device (e.g. unit tests), you may like to look into running the device emulator. This may get you more control than trying to use a physical device.