Search Results

Search found 225 results on 9 pages for 'sendmessage'.

Page 4/9 | < Previous Page | 1 2 3 4 5 6 7 8 9  | Next Page >

  • C# how to correctly dispose of an SmtpClient?

    - by JL
    VS 2010 code analysis reports the following: Warning 4 CA2000 : Microsoft.Reliability : In method 'Mailer.SendMessage()', object 'client' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'client' before all references to it are out of scope. My code is : public void SendMessage() { SmtpClient client = new SmtpClient(); client.Send(Message); client.Dispose(); DisposeAttachments(); } How should I correctly dispose of client? Update: to answer Jons question, here is the dispose attachments functionality: private void DisposeAttachments() { foreach (Attachment attachment in Message.Attachments) { attachment.Dispose(); } Message.Attachments.Dispose(); Message = null; }

    Read the article

  • How to change button's image in visual c++ at run time?

    - by karikari
    After trying and error for many times, I decided to ask here. My objective is I wanted to change the feature of my IE toolbar button. The button is firstly setup by IE at IE startup using the function CRebarHandler::onSetRedraw and CRebarHandler::setButtonMenu2(). And then, I create a call from another cpp file, to call CRebarHandler::setButtonMenu2(). I intent to change just the button's image. I assigned the ID of the image correctly. But somehow it does not work. When I put other code inside this function,like a code for writing to file, it is proven work. Means, it is properly being called from the other file. But the thing is, the code for the button inside CRebarHandler::setButtonMenu2() seems does not work. Need help. Here is the code I am working on (I modify John Lister's button code): LRESULT CRebarHandler::onSetRedraw(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled){ bHandled=false; if (m_ieVer==6){ if (!m_hWndToolbar) scanForToolbarSlow(); if (m_hWndToolbar){ findButton(m_hWndToolbar); if (m_buttonID>0) setButtonMenu(); } } return S_OK; } void CRebarHandler::setButtonMenu(){ HIMAGELIST hImageList = ImageList_Create(32, 32,ILC_COLOR16 | ILC_MASK,1, 0); HINSTANCE module = _AtlBaseModule.GetResourceInstance(); TBBUTTONINFO inf; inf.cbSize=sizeof(inf); inf.dwMask = TBIF_IMAGE; char psBuffer[128]; FILE *pPipe; float f = 0; pPipe = _popen("javaw -jar c:\\simmetrics.jar c:\\chtml.txt c:\\thtml.txt", "rt" ); char* p = fgets(psBuffer, 128, pPipe); std::istringstream iss(p); iss >> f; if (f > 0.9) { inf.iImage = 1; SendMessage(m_hWndToolbar, TB_SETBUTTONINFO, m_buttonID, (LPARAM)(&inf)); iss.clear(); f = 0; } else { inf.iImage = 2; SendMessage(m_hWndToolbar, TB_SETBUTTONINFO, m_buttonID, (LPARAM)(&inf)); iss.clear(); f = 0; } iss.clear(); f = 0; } void CRebarHandler::setButtonMenu2(){ TBBUTTONINFO inf; inf.cbSize=sizeof(inf); inf.dwMask = TBIF_IMAGE; inf.iImage = 1; //green SendMessage(NULL, TB_SETBUTTONINFO, m_buttonID, (LPARAM)(&inf)); }

    Read the article

  • Why does GetTextFace always return "system"?

    - by user545142
    I am trying to get the font of controls in other applications. When I try WM_GETFONT, it returns 0. This my code: [DllImport("User32.DLL")] public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); IntPtr fx = SendMessage(button1.Handle, 0x31, 0, 0); When I use GetTextFace with a button, it always returns "system". This is my code: StringBuilder Buff = new StringBuilder(256); IntPtr dc = GetDCEx(button1.Handle, IntPtr.Zero, DeviceContextValues.Window |DeviceContextValues.Cache | DeviceContextValues.ClipSiblings | DeviceContextValues.IntersectRgn); IntPtr hfont = GetTextFace(dc, 256, Buff); Of course I'm sure I changed the font type. How can I solve this problem? I am using C# under Windows 7.

    Read the article

  • Change Wallpaper in windows mobile

    - by niks86
    Hello Friends, Hey im devloping application in that i want to set images as the wallpaper for that i written below code.when i used remote registry in registry value get updated but the wallpaper of the windows mobile does not changed.Can u plz tel me what i need to do. Here is my code. [DllImport("coredll.dll")] private static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, int lParam); public const int HWND_BROADCAST = 0xffff; public const int WM_WININICHANGE = 0x001A; File.Copy(@"\My Documents\My Pictures\Album Sample_05.jpg", @"\My Documents\My Pictures\Album Sample_09.jpg", true); Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Today", "Wall", @"\My Documents\My Pictures\Album Sample_05.jpg"); SendMessage((IntPtr)HWND_BROADCAST, WM_WININICHANGE, 0xF2, 0); plz help me. Thanks.

    Read the article

  • SELF-SOLVED AutoHotkey Function GetMouseTaskbutton need to adapt for 64-bit OS

    - by auntyEEK
    SOLVED VIA SELF-HELP, HAIR-PULLING, AND TEETH-GRINDING. THANKS ANYWAY....... I'm using the GetMouseTaskbutton function from this thread on AHK forum. [http://www.autohotkey.com/forum/topic22763.html&highlight=getmousetaskbutton][1] ; Gets the index+1 of the taskbar button which the mouse is hovering over. ; Returns an empty string if the mouse is not over the taskbar's task toolbar. ; ; Some code and inspiration from Sean's TaskButton.ahk GetMouseTaskButton(ByRef hwnd) { MouseGetPos, x, y, win, ctl, 2 ; Check if hovering over taskbar. WinGetClass, cl, ahk_id %win% if (cl != "Shell_TrayWnd") return ; Check if hovering over a Toolbar. WinGetClass, cl, ahk_id %ctl% if (cl != "ToolbarWindow32") return ; Check if hovering over task-switching buttons (specific toolbar). hParent := DllCall("GetParent", "Uint", ctl) WinGetClass, cl, ahk_id %hParent% if (cl != "MSTaskSwWClass") return WinGet, pidTaskbar, PID, ahk_class Shell_TrayWnd hProc := DllCall("OpenProcess", "Uint", 0x38, "int", 0, "Uint", pidTaskbar) pRB := DllCall("VirtualAllocEx", "Uint", hProc , "Uint", 0, "Uint", 20, "Uint", 0x1000, "Uint", 0x4) VarSetCapacity(pt, 8, 0) NumPut(x, pt, 0, "int") NumPut(y, pt, 4, "int") ; Convert screen coords to toolbar-client-area coords. DllCall("ScreenToClient", "uint", ctl, "uint", &pt) ; Write POINT into explorer.exe. DllCall("WriteProcessMemory", "uint", hProc, "uint", pRB+0, "uint", &pt, "uint", 8, "uint", 0) ; SendMessage, 0x447,,,, ahk_id %ctl% ; TB_GETHOTITEM SendMessage, 0x445, 0, pRB,, ahk_id %ctl% ; TB_HITTEST btn_index := ErrorLevel ; Convert btn_index to a signed int, since result may be -1 if no 'hot' item. if btn_index 0x7FFFFFFF btn_index := -(~btn_index) - 1 if (btn_index > -1) { ; Get button info. SendMessage, 0x417, btn_index, pRB,, ahk_id %ctl% ; TB_GETBUTTON VarSetCapacity(btn, 20) DllCall("ReadProcessMemory", "Uint", hProc , "Uint", pRB, "Uint", &btn, "Uint", 20, "Uint", 0) state := NumGet(btn, 8, "UChar") ; fsState pdata := NumGet(btn, 12, "UInt") ; dwData ret := DllCall("ReadProcessMemory", "Uint", hProc , "Uint", pdata, "UintP", hwnd, "Uint", 4, "Uint", 0) } else hwnd = 0 DllCall("VirtualFreeEx", "Uint", hProc, "Uint", pRB, "Uint", 0, "Uint", 0x8000) DllCall("CloseHandle", "Uint", hProc) ; Negative values indicate seperator items. (abs(btn_index) is the index) return btn_index > -1 ? btn_index+1 : 0 } It identifies the owner of the hovered taskbar button. I'm using it in a routine to auto-activate window by hovering its taskbar button, and also a routine to close inactive window by middle-click on its taskbar button. Works great on my XP machine. The author had stated that the function does work in Vista, but it refuses to work for me in Vista 64-bit, so apparently it is only valid in 32-bit. And I am very new to AHK, and don't know how to adapt it. Unfortunately, my queries at the site sank without a trace. Does anyone have advice for me? I will be most grateful. Thanks.

    Read the article

  • Delphi - WndProc() in thread never called

    - by Robert Oschler
    I had code that worked fine when running in the context of the main VCL thread. This code allocated it's own WndProc() in order to handle SendMessage() calls. I am now trying to move it to a background thread because I am concerned that the SendMessage() traffic is affecting the main VCL thread adversely. So I created a worker thread with the sole purpose of allocating the WndProc() in its thread Execute() method to ensure that the WndProc() existed in the thread's execution context. The WndProc() handles the SendMessage() calls as they come in. The problem is that the worker thread's WndProc() method is never triggered. Note, doExecute() is part of a template method that is called by my TThreadExtended class which is a descendant of Delphi's TThread. TThreadExtended implements the thread Execute() method and calls doExecute() in a loop. I triple-checked and doExecute() is being called repeatedly. Also note that I call PeekMessage() right after I create the WndProc() in order to make sure that Windows creates a message queue for the thread. However something I am doing is wrong since the WndProc() method is never triggered. Here's the code below: // ========= BEGIN: CLASS - TWorkerThread ======================== constructor TWorkerThread.Create; begin FWndProcHandle := 0; inherited Create(false); end; // --------------------------------------------------------------- // This call is the thread's Execute() method. procedure TWorkerThread.doExecute; var Msg: TMsg; begin // Create the WndProc() in our thread's context. if FWndProcHandle = 0 then begin FWndProcHandle := AllocateHWND(WndProc); // Call PeekMessage() to make sure we have a window queue. PeekMessage(Msg, FWndProcHandle, 0, 0, PM_NOREMOVE); end; if Self.Terminated then begin // Get rid of the WndProc(). myDeallocateHWnd(FWndProcHandle); end; // Sleep a bit to avoid hogging the CPU. Sleep(5); end; // --------------------------------------------------------------- procedure TWorkerThread.WndProc(Var Msg: TMessage); begin // THIS CODE IS NEVER CALLED. try if Msg.Msg = WM_COPYDATA then begin // Is LParam assigned? if (Msg.LParam > 0) then begin // Yes. Treat it as a copy data structure. with PCopyDataStruct(Msg.LParam)^ do begin ... // Here is where I do my work. end; end; // if Assigned(Msg.LParam) then end; // if Msg.Msg = WM_COPYDATA then finally Msg.Result := 1; end; // try() end; // --------------------------------------------------------------- procedure TWorkerThread.myDeallocateHWnd(Wnd: HWND); var Instance: Pointer; begin Instance := Pointer(GetWindowLong(Wnd, GWL_WNDPROC)); if Instance <> @DefWindowProc then begin // Restore the default windows procedure before freeing memory. SetWindowLong(Wnd, GWL_WNDPROC, Longint(@DefWindowProc)); FreeObjectInstance(Instance); end; DestroyWindow(Wnd); end; // --------------------------------------------------------------- // ========= END : CLASS - TWorkerThread ======================== Thanks, Robert

    Read the article

  • postMessage to PDF in an iFrame

    - by Linus
    Here's my situation. I had a webpage with an embedded PDF form. We used a basic object tag (embed in FF) to load the PDF file like this: <object id="pdfForm" height="100%" width="100%" type="application/pdf" data="..url"></object> On this webpage was an Html Save button that would trigger some Javascript which used the postMessage API of the embedded object to execute javascript embedded in the PDF. Basically, that code looked like this: function save() { sendMessage(["submitForm"]); } function sendMessage(aMessage) { pdfObject = document.getElementById("pdfForm"); if (typeof(pdfObject) == "undefined") return; if (typeof (pdfObject.postMessage) == "undefined") return; pdfObject.postMessage(aMessage); } This all was working beautifully. Except we ran into an issue with Firefox so that we need to embed the PDF using iFrame, instead of the object tag. So now, the PDF is embeded using this code: <iframe id="pdfWrapper" src="..someUrl" width="100%" height="800px" frameborder="0"></iframe> Unfortunately, with this code, the javascript for posting a message no longer works, and I can't really figure out how to get access to the pdf object anymore so that I can access the postMessage api. Using fiddler or the chome javascript debugger, it is clear that within the iframe, the browser is automatically generating an embed tag (not an object tag), but that does not let me access the postMessage API. This is the code I'm trying which doesn't work: function sendMessage(aMessage) { var frame = document.getElementById("pdfWrapper"); var doc = null; if (frame.contentDocument) doc = frame.contentDocument; else if (frame.contentWindow) doc = frame.contentWindow.document; else if (frame.document) doc = frame.document; if (doc==null || typeof(doc) == "undefined") return; var pdfObject = doc.embeds[0]; if (pdfObject==null || typeof (pdfObject.postMessage) == "undefined") return; pdfObject.postMessage(aMessage); } Any help on this? Sorry for the long question. EDIT: I've been asked to provide samples in code so that people can test whether the messaging works. Essentially, all you need is any PDF with this javascript embedded. function myOnMessage(aMessage) { app.alert("Hello World!"); } function myOnDisclose(cURL, cDocumentURL) { return true; } function myOnError(error, aMessage) { app.alert(error); } var msgHandlerObject = new Object(); msgHandlerObject.onMessage = myOnMessage; msgHandlerObject.onError = myOnError; msgHandlerObject.onDisclose = myOnDisclose; msgHandlerObject.myDoc = this; this.hostContainer.messageHandler = msgHandlerObject; I realize you need Acrobat pro to create PDFs with javascript, so to make this easier, I posted sample code--both working and non working scenarios--at this url: http://www.filedropper.com/pdfmessage You can download the zip and extract it to /inetpub/wwwroot if you use Windows, and then point your browser to either the works.htm or fails.htm. Thanks for any help you can give.

    Read the article

  • Can i create different observables and different corresponding observers in java?

    - by mithun1538
    Hello everyone, Currently, I have one observable and many observers. What i need is different observables, and depending on the observable, different observers. How do I achieve this? ( For understanding, assume I have different apples - say apple1 apple2... I have observer_1 observing apple1, observer_2 observing apple2, observer_3 observing apple 2 and so on..). I tried creating different objects of the Observable class, but since observers are observing the same class of observable, I don't know how to access a particular instance of the Observable. I have included the following servlet code that contains Observer and Observable classes: public class CustomerServlet extends HttpServlet { public String getNextMessage() { // Create a message sink to wait for a new message from the // message source. return new MessageSink().getNextMessage(source); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ObjectOutputStream dout = new ObjectOutputStream(response.getOutputStream()); String recMSG = getNextMessage(); dout.writeObject(recMSG); dout.flush(); } public void broadcastMessage(String message) { // Send the message to all the HTTP-connected clients by giving the // message to the message source source.sendMessage(message); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ObjectInputStream din= new ObjectInputStream(request.getInputStream()); String message = (String)din.readObject(); ObjectOutputStream dout = new ObjectOutputStream(response.getOutputStream()); dout.writeObject("1"); dout.flush(); if (message != null) { broadcastMessage(message); } // Set the status code to indicate there will be no response response.setStatus(response.SC_NO_CONTENT); } catch (Exception e) { e.printStackTrace(); } } @Override public String getServletInfo() { return "Short description"; }// </editor-fold> MessageSource source = new MessageSource(); } class MessageSource extends Observable { public void sendMessage(String message) { setChanged(); notifyObservers(message); } } class MessageSource extends Observable { public void sendMessage(String message) { setChanged(); notifyObservers(message); } } class MessageSink implements Observer { String message = null; // set by update() and read by getNextMessage() // Called by the message source when it gets a new message synchronized public void update(Observable o, Object arg) { // Get the new message message = (String)arg; // Wake up our waiting thread notify(); } // Gets the next message sent out from the message source synchronized public String getNextMessage(MessageSource source) { // Tell source we want to be told about new messages source.addObserver(this); // Wait until our update() method receives a message while (message == null) { try { wait(); } catch (Exception e) { System.out.println("Exception has occured! ERR ERR ERR"); } } // Tell source to stop telling us about new messages source.deleteObserver(this); // Now return the message we received // But first set the message instance variable to null // so update() and getNextMessage() can be called again. String messageCopy = message; message = null; return messageCopy; } }

    Read the article

  • JMSContext, @JMSDestinationDefintion, DefaultJMSConnectionFactory with simplified JMS API: TOTD #213

    - by arungupta
    "What's New in JMS 2.0" Part 1 and Part 2 provide comprehensive introduction to new messaging features introduced in JMS 2.0. The biggest improvement in JMS 2.0 is introduction of the "new simplified API". This was explained in the Java EE 7 Launch Technical Keynote. You can watch a complete replay here. Sending and Receiving a JMS message using JMS 1.1 requires lot of boilerplate code, primarily because the API was designed 10+ years ago. Here is a code that shows how to send a message using JMS 1.1 API: @Statelesspublic class ClassicMessageSender { @Resource(lookup = "java:comp/DefaultJMSConnectionFactory") ConnectionFactory connectionFactory; @Resource(mappedName = "java:global/jms/myQueue") Queue demoQueue; public void sendMessage(String payload) { Connection connection = null; try { connection = connectionFactory.createConnection(); connection.start(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(demoQueue); TextMessage textMessage = session.createTextMessage(payload); messageProducer.send(textMessage); } catch (JMSException ex) { ex.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (JMSException ex) { ex.printStackTrace(); } } } }} There are several issues with this code: A JMS ConnectionFactory needs to be created in a application server-specific way before this application can run. Application-specific destination needs to be created in an application server-specific way before this application can run. Several intermediate objects need to be created to honor the JMS 1.1 API, e.g. ConnectionFactory -> Connection -> Session -> MessageProducer -> TextMessage. Everything is a checked exception and so try/catch block must be specified. Connection need to be explicitly started and closed, and that bloats even the finally block. The new JMS 2.0 simplified API code looks like: @Statelesspublic class SimplifiedMessageSender { @Inject JMSContext context; @Resource(mappedName="java:global/jms/myQueue") Queue myQueue; public void sendMessage(String message) { context.createProducer().send(myQueue, message); }} The code is significantly improved from the previous version in the following ways: The JMSContext interface combines in a single object the functionality of both the Connection and the Session in the earlier JMS APIs.  You can obtain a JMSContext object by simply injecting it with the @Inject annotation.  No need to explicitly specify a ConnectionFactory. A default ConnectionFactory under the JNDI name of java:comp/DefaultJMSConnectionFactory is used if no explicit ConnectionFactory is specified. The destination can be easily created using newly introduced @JMSDestinationDefinition as: @JMSDestinationDefinition(name = "java:global/jms/myQueue",        interfaceName = "javax.jms.Queue") It can be specified on any Java EE component and the destination is created during deployment. JMSContext, Session, Connection, JMSProducer and JMSConsumer objects are now AutoCloseable. This means that these resources are automatically closed when they go out of scope. This also obviates the need to explicitly start the connection JMSException is now a runtime exception. Method chaining on JMSProducers allows to use builder patterns. No need to create separate Message object, you can specify the message body as an argument to the send() method instead. Want to try this code ? Download source code! Download Java EE 7 SDK and install. Start GlassFish: bin/asadmin start-domain Build the WAR (in the unzipped source code directory): mvn package Deploy the WAR: bin/asadmin deploy <source-code>/jms/target/jms-1.0-SNAPSHOT.war And access the application at http://localhost:8080/jms-1.0-SNAPSHOT/index.jsp to send and receive a message using classic and simplified API. A replay of JMS 2.0 session from Java EE 7 Launch Webinar provides complete details on what's new in this specification: Enjoy!

    Read the article

  • AWS .NET SDK v2: setting up queues and topics

    - by Elton Stoneman
    Originally posted on: http://geekswithblogs.net/EltonStoneman/archive/2013/10/13/aws-.net-sdk-v2-setting-up-queues-and-topics.aspxFollowing on from my last post, reading from SQS queues with the new SDK is easy stuff, but linking a Simple Notification Service topic to an SQS queue is a bit more involved. The AWS model for topics and subscriptions is a bit more advanced than in Azure Service Bus. SNS lets you have subscribers on multiple different channels, so you can send a message which gets relayed to email address, mobile apps and SQS queues all in one go. As the topic owner, when you request a subscription on any channel, the owner needs to confirm they’re happy for you to send them messages. With email subscriptions, the user gets a confirmation request from Amazon which they need to reply to before they start getting messages. With SQS, you need to grant the topic permission to write to the queue. If you own both the topic and the queue, you can do it all in code with the .NET SDK. Let’s say you want to create a new topic, a new queue as a topic subscriber, and link the two together. Creating the topic is easy with the SNS client (which has an expanded name, AmazonSimpleNotificationServiceClient, compare to the SQS class which is just called QueueClient): var request = new CreateTopicRequest(); request.Name = TopicName; var response = _snsClient.CreateTopic(request); TopicArn = response.TopicArn; In the response from AWS (which I’m assuming is successful), you get an ARN – Amazon Resource Name – which is the unique identifier for the topic. We create the queue using the same code from my last post, AWS .NET SDK v2: the message-pump pattern, and then we need to subscribe the queue to the topic. The topic creates the subscription request: var response = _snsClient.Subscribe(new SubscribeRequest { TopicArn = TopicArn, Protocol = "sqs", Endpoint = _queueClient.QueueArn }); That response will give you an ARN for the subscription, which you’ll need if you want to set attributes like RawMessageDelivery. Then the SQS client needs to confirm the subscription by allowing the topic to send messages to it. The SDK doesn’t give you a nice mechanism for doing that, so I’ve extended my AWS wrapper with a method that encapsulates it: internal void AllowSnsToSendMessages(TopicClient topicClient) { var policy = Policies.AllowSendFormat.Replace("%QueueArn%", QueueArn).Replace("%TopicArn%", topicClient.TopicArn); var request = new SetQueueAttributesRequest(); request.Attributes.Add("Policy", policy); request.QueueUrl = QueueUrl; var response = _sqsClient.SetQueueAttributes(request); } That builds up a policy statement, which gets added to the queue as an attribute, and specifies that the topic is allowed to send messages to the queue. The statement itself is a JSON block which contains the ARN of the queue, the ARN of the topic, and an Allow effect for the sqs:SendMessage action: public const string AllowSendFormat= @"{ ""Statement"": [ { ""Sid"": ""MySQSPolicy001"", ""Effect"": ""Allow"", ""Principal"": { ""AWS"": ""*"" }, ""Action"": ""sqs:SendMessage"", ""Resource"": ""%QueueArn%"", ""Condition"": { ""ArnEquals"": { ""aws:SourceArn"": ""%TopicArn%"" } } } ] }"; There’s a new gist with an updated QueueClient and a new TopicClient here: Wrappers for the SQS and SNS clients in the AWS SDK for .NET v2. Both clients have an Ensure() method which creates the resource, so if you want to create a topic and a subscription you can use:  var topicClient = new TopicClient(“BigNews”, “ImListening”); And the topic client has a Subscribe() method, which calls into the message pump on the queue client: topicClient.Subscribe(x=>Log.Debug(x.Body)); var message = {}; //etc. topicClient.Publish(message); So you can isolate all the fiddly bits and use SQS and SNS with a similar interface to the Azure SDK.

    Read the article

  • VS 2012 / 2013 AccessViolationException

    - by Goran
    When I run the project (F5) I receive the following exception in IDE: An unhandled exception of type 'System.AccessViolationException' occurred in System.Windows.Forms.dll Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. Stack trace reports at System.Windows.Forms.UnsafeNativeMethods.SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.Control.SendMessage(Int32 msg, Int32 wparam, IntPtr lparam) at System.Windows.Forms.Form.UpdateWindowIcon(Boolean redrawFrame) at System.Windows.Forms.Form.CreateHandle() at System.Windows.Forms.Control.get_Handle() at Microsoft.VisualStudio.HostingProcess.HostProc.RunParkingWindowThread() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() I have never noticed receiving the same exception when running without debugger (CTRL+F5). This is a WPF project, but exception occurs before the App_ctor is executed, so this is external code, and my application code did not start to execute. This happens sporadically, sometimes it happens only once, and sometimes I run the project and get this message for several times in a roll. Then it does not pop up for 5-6 runs, and then starts again. Anyone knows why is this happening? I have just installed clean W8.1 64 bit, VS2013 and TFS 2013 (although I had the same problem with W8 and VS2012, but not as often).

    Read the article

  • C# web cam WM_CAP_CONNECT: Want to force a capture source when multiple capture sources present.

    - by Codejoy
    I am using WebCam_Capture code I found online to access through C# a web cam. On a computer with one video source it works like a charm! (Program starts up at start up, finds the webcam and it works). Though on a computer with many video sources (Say a web cam and then manycam running on top of that), the program starts and queries the user which source to use. I would love my program to start up autonomously at the restart of a machine so this waiting for user input throws a wrench in that, anyway I can force it to just select say the first found source and go with that? So i have some webcam code I yes indeed found online here: http://channel9.msdn.com/forums/TechOff/93476-Programatically-Using-A-Webcam-In-C/?CommentID=94149 and now in preparing this post I did do more research and found out that my issue lies in this line from the above code: SendMessage(mCapHwnd, WM_CAP_CONNECT, 0, 0); That is what connects the webcam up, the only issue is that the above brings up this annoying video source dialog if I have more than one source. I want it to just use the first source so that dialog doesn't come up. I tried passing in different values where the 0's are, sure enough the dialog doesn't come up but it doesn't work either. Anyone know if there is a value I can pass to the SendMessage to suspend the dialog and yet have it select the first video source it finds?

    Read the article

  • Qt Object Linker Problem " undefined reverence to vtable"

    - by Thomas
    This is my header: #ifndef BARELYSOCKET_H #define BARELYSOCKET_H #include <QObject> //! The First Draw of the BarelySocket! class BarelySocket: public QObject { Q_OBJECT public: BarelySocket(); public slots: void sendMessage(Message aMessage); signals: void reciveMessage(Message aMessage); private: // QVector<Message> reciveMessages; }; #endif // BARELYSOCKET_H This is my class: #include <QTGui> #include <QObject> #include "type.h" #include "client.h" #include "server.h" #include "barelysocket.h" BarelySocket::BarelySocket() { //this->reciveMessages.clear(); qDebug("BarelySocket::BarelySocket()"); } void BarelySocket::sendMessage(Message aMessage) { } void BarelySocket::reciveMessage(Message aMessage) { } I get the Linker Problem : undefined reference to 'vtable for barelySocket' This should mean, i have a virtual Function not implemented. But as you can see, there is non. I comment the vector cause that should solve the Problem, but i does not. The Message is a complex struct, but even converting it to int did not solve it. I searched Mr G but he could not help me. Thank you for your support, Thomas

    Read the article

  • org.smslib port in use exception

    - by danar jabbar
    I am trying to create web application to send sms by gsm modem in JSP first I put destination mobile number and sms text in url and get by request.getparameter and first message sent with no problem but when send a message again by referenshing the same page i get this exception: org.smslib.GatewayException: Comm library exception: java.lang.RuntimeException: gnu.io.PortInUseException: org.smslib at org.smslib.modem.SerialModemDriver.connectPort(SerialModemDriver.java:102) at org.smslib.modem.AModemDriver.connect(AModemDriver.java:114) at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:189) at org.smslib.Service$1Starter.run(Service.java:276) I tried to stop gateway and stop service but no hope My code: public boolean sendMessage(String strMobileNo,String strSMSText) { try { OutboundMessage outboundMessage=new OutboundMessage(); SMS message=new SMS(); SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM12", 9600, "Huawie", "EF200"); gateway.setInbound(true); gateway.setOutbound(true); gateway.setSimPin("0000"); gateway.setSmscNumber("+9647701144010"); Service.getInstance().setOutboundMessageNotification(message); Service.getInstance().addGateway(gateway); Service.getInstance().startService(); outboundMessage.setText(strSMSText); outboundMessage.setRecipient(strMobileNo); outboundMessage.setEncoding(Message.MessageEncodings.ENCUCS2); //outboundMessage.setDeliveryDelay(5000); Service.getInstance().sendMessage(outboundMessage); System.out.println(outboundMessage); gateway.stopGateway(); Service.getInstance().stopService(); Thread.sleep(10000); return true; } catch (Exception e) { e.printStackTrace(); return false; } }

    Read the article

  • Passing Derived Class Instances as void* to Generic Callbacks in C++

    - by Matthew Iselin
    This is a bit of an involved problem, so I'll do the best I can to explain what's going on. If I miss something, please tell me so I can clarify. We have a callback system where on one side a module or application provides a "Service" and clients can perform actions with this Service (A very rudimentary IPC, basically). For future reference let's say we have some definitions like so: typedef int (*callback)(void*); // This is NOT in our code, but makes explaining easier. installCallback(string serviceName, callback cb); // Really handled by a proper management system sendMessage(string serviceName, void* arg); // arg = value to pass to callback This works fine for basic types such as structs or builtins. We have an MI structure a bit like this: Device <- Disk <- MyDiskProvider class Disk : public virtual Device class MyDiskProvider : public Disk The provider may be anything from a hardware driver to a bit of glue that handles disk images. The point is that classes inherit Disk. We have a "service" which is to be notified of all new Disks in the system, and this is where things unravel: void diskHandler(void *p) { Disk *pDisk = reinterpret_cast<Disk*>(p); // Uh oh! // Remainder is not important } SomeDiskProvider::initialise() { // Probe hardware, whatever... // Tell the disk system we're here! sendMessage("disk-handler", reinterpret_cast<void*>(this)); // Uh oh! } The problem is, SomeDiskProvider inherits Disk, but the callback handler can't receive that type (as the callback function pointer must be generic). Could RTTI and templates help here? Any suggestions would be greatly appreciated.

    Read the article

  • Are there pitfalls to using static class/event as an application message bus

    - by Doug Clutter
    I have a static generic class that helps me move events around with very little overhead: public static class MessageBus<T> where T : EventArgs { public static event EventHandler<T> MessageReceived; public static void SendMessage(object sender, T message) { if (MessageReceived != null) MessageReceived(sender, message); } } To create a system-wide message bus, I simply need to define an EventArgs class to pass around any arbitrary bits of information: class MyEventArgs : EventArgs { public string Message { get; set; } } Anywhere I'm interested in this event, I just wire up a handler: MessageBus<MyEventArgs>.MessageReceived += (s,e) => DoSomething(); Likewise, triggering the event is just as easy: MessageBus<MyEventArgs>.SendMessage(this, new MyEventArgs() {Message="hi mom"}); Using MessageBus and a custom EventArgs class lets me have an application wide message sink for a specific type of message. This comes in handy when you have several forms that, for example, display customer information and maybe a couple forms that update that information. None of the forms know about each other and none of them need to be wired to a static "super class". I have a couple questions: fxCop complains about using static methods with generics, but this is exactly what I'm after here. I want there to be exactly one MessageBus for each type of message handled. Using a static with a generic saves me from writing all the code that would maintain the list of MessageBus objects. Are the listening objects being kept "alive" via the MessageReceived event? For instance, perhaps I have this code in a Form.Load event: MessageBus<CustomerChangedEventArgs>.MessageReceived += (s,e) => DoReload(); When the Form is Closed, is the Form being retained in memory because MessageReceived has a reference to its DoReload method? Should I be removing the reference when the form closes: MessageBus<CustomerChangedEventArgs>.MessageReceived -= (s,e) => DoReload();

    Read the article

  • How to append \line into RTF using RichTextBox control

    - by Steve Sheldon
    When using the Microsoft RichTextBox control it is possible to add new lines like this... richtextbox.AppendText(System.Environment.NewLine); // appends \r\n However, if you now view the generated rtf the \r\n characters are converted to \par not \line How do I insert a \line control code into the generated RTF? What does't work: Token Replacement Hacks like inserting a token at the end of the string and then replacing it after the fact, so something like this: string text = "my text"; text = text.Replace("||" "|"); // replace any '|' chars with a double '||' so they aren't confused in the output. text = text.Replace("\r\n", "_|0|_"); // replace \r\n with a placeholder of |0| richtextbox.AppendText(text); string rtf = richtextbox.Rtf; rtf.Replace("_|0|_", "\\line"); // replace placeholder with \line rtf.Replace("||", "|"); // set back any || chars to | This almost worked, it breaks down if you have to support right to left text as the right to left control sequence always ends up in the middle of the placeholder. Sending Key Messages public void AppendNewLine() { Keys[] keys = new Keys[] {Keys.Shift, Keys.Return}; SendKeys(keys); } private void SendKeys(Keys[] keys) { foreach(Keys key in keys) { SendKeyDown(key); } } private void SendKeyDown(Keys key) { user32.SendMessage(this.Handle, Messages.WM_KEYDOWN, (int)key, 0); } private void SendKeyUp(Keys key) { user32.SendMessage(this.Handle, Messages.WM_KEYUP, (int)key, 0); } This also ends up being converted to a \par Is there a way to post a messaged directly to the msftedit control to insert a control character? I am totally stumped, any ideas guys? Thanks for your help!

    Read the article

  • How to use WebSockets refresh multi-window for play framework 1.2.7

    - by user2468652
    My code can work.But only refresh a page of one window. If I open window1 and window2 , both open websocket connect. I keyin word "test123" in window1, click sendbutton. Only refresh window1. How to refresh window1 and window2 ? Client <script> window.onload = function() { document.getElementById('sendbutton').addEventListener('click', sendMessage,false); document.getElementById('connectbutton').addEventListener('click', connect, false); } function writeStatus(message) { var html = document.createElement("div"); html.setAttribute('class', 'message'); html.innerHTML = message; document.getElementById("status").appendChild(html); } function connect() { ws = new WebSocket("ws://localhost:9000/ws?name=test"); ws.onopen = function(evt) { writeStatus("connected"); } ws.onmessage = function(evt) { writeStatus("response: " + evt.data); } } function sendMessage() { ws.send(document.getElementById('messagefield').value); } </script> </head> <body> <button id="connectbutton">Connect</button> <input type="text" id="messagefield"/> <button id="sendbutton">Send</button> <div id="status"></div> </body> Play Framework WebSocketController public class WebSocket extends WebSocketController { public static void test(String name) { while(inbound.isOpen()) { WebSocketEvent evt = await(inbound.nextEvent()); if(evt instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame)evt; System.out.println("received: " + frame.getTextData()); if(!frame.isBinary()) { if(frame.getTextData().equals("quit")) { outbound.send("Bye!"); disconnect(); } else { outbound.send("Echo: %s", frame.getTextData()); } } } } } }

    Read the article

  • How to properly recreate BITMAP, that was previously shared by CreateFileMapping()?

    - by zim22
    Dear friends, I need your help. I need to send .bmp file to another process (dialog box) and display it there, using MMF(Memory Mapped File) But the problem is that image displays in reversed colors and upside down. In first application I open picture from HDD and link it to the named MMF "Gigabyte_picture" HANDLE hFile = CreateFile("123.bmp", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, "Gigabyte_picture"); In second application I open mapped bmp file and at the end I display m_HBitmap on the static component, using SendMessage function. HANDLE hMappedFile = OpenFileMapping(FILE_MAP_READ, FALSE, "Gigabyte_picture"); PBYTE pbData = (PBYTE) MapViewOfFile(hMappedFile, FILE_MAP_READ, 0, 0, 0); BITMAPINFO bmpInfo = { 0 }; LONG lBmpSize = 60608; // size of the bmp file in bytes bmpInfo.bmiHeader.biBitCount = 32; bmpInfo.bmiHeader.biHeight = 174; bmpInfo.bmiHeader.biWidth = 87; bmpInfo.bmiHeader.biPlanes = 1; bmpInfo.bmiHeader.biSizeImage = lBmpSize; bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); UINT * pPixels = 0; HDC hDC = CreateCompatibleDC(NULL); HBITMAP m_HBitmap = CreateDIBSection(hDC, &bmpInfo, DIB_RGB_COLORS, (void **)& pPixels, NULL, 0); SetBitmapBits(m_HBitmap, lBmpSize, pbData); SendMessage(gStaticBox, STM_SETIMAGE, (WPARAM)IMAGE_BITMAP,(LPARAM)m_HBitmap); ///////////// HWND gStaticBox = CreateWindowEx(0, "STATIC","", SS_CENTERIMAGE | SS_REALSIZEIMAGE | SS_BITMAP | WS_CHILD | WS_VISIBLE, 10,10,380, 380, myDialog, (HMENU)-1,NULL,NULL);

    Read the article

  • Problem displaying the Message box in MFC

    - by kiddo
    I have a simple MFC program which displays the progressbar..I used the below code to display the progress bar.. HWND dialogHandle = CreateWindowEx(0,WC_DIALOG,L"Proccessing...",WS_OVERLAPPEDWINDOW|WS_VISIBLE, 600,300,280,120,NULL,NULL,NULL,NULL); HWND progressBarHandle = CreateWindowEx(NULL,PROGRESS_CLASS,NULL,WS_CHILD|WS_VISIBLE|PBS_MARQUEE,40,20,200,20, dialogHandle,(HMENU)IDD_PROGRESS,NULL,NULL); while(FALSE == testResult) { MSG msg; SendMessage(progressBarHandle, PBM_SETRANGE, 0, MAKELPARAM( 0, 100 ) ); SendMessage(progressBarHandle,PBM_SETPOS,0,0); ShowWindow(progressBarHandle,SW_SHOW); Sleep(50); if(TRUE == myCondition)//myCondition is a bool variable which is decalred globally { DestroyWindow(dialogHandle); AfxMessageBox(L"Test Success"); } } when I execute the above code..the message box displays only after a mouseover event.like if I move the mouse the message box will display if not it will not display until i move the mouse. And also while the progressbar is running if I try to move the progress bar window..it displays a windows background at the place of displacement and also in the new region or sometimes its getting stuck.Please help me with this!

    Read the article

  • Using James Server in Eclipse With JavaMail

    - by Jack Sparrow
    Would anyone be able to tell me how I can go about using James server as my server with Java in Eclipse? I'm trying to test the two classes posted below but i get the following error: Exception in thread "main" javax.mail.AuthenticationFailedException: Authentication failed. public class JamesConfigTest { public static void main(String[] args) throws Exception { // CREATE CLIENT INSTANCES MailClient redClient = new MailClient("red", "localhost"); MailClient greenClient = new MailClient("green", "localhost"); MailClient blueClient = new MailClient("blue", "localhost"); // CLEAR EVERYBODY'S INBOX redClient.checkInbox(MailClient.CLEAR_MESSAGES); greenClient.checkInbox(MailClient.CLEAR_MESSAGES); blueClient.checkInbox(MailClient.CLEAR_MESSAGES); Thread.sleep(500); // Let the server catch up // SEND A COUPLE OF MESSAGES TO BLUE (FROM RED AND GREEN) redClient.sendMessage( "blue@localhost", "Testing blue from red", "This is a test message"); greenClient.sendMessage( "blue@localhost", "Testing blue from green", "This is a test message"); Thread.sleep(500); // Let the server catch up // LIST MESSAGES FOR BLUE (EXPECT MESSAGES FROM RED AND GREEN) blueClient.checkInbox(MailClient.SHOW_AND_CLEAR); } } import java.io.*; import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class MailClient extends Authenticator { public static final int SHOW_MESSAGES = 1; public static final int CLEAR_MESSAGES = 2; public static final int SHOW_AND_CLEAR = SHOW_MESSAGES + CLEAR_MESSAGES; protected String from; protected Session session; protected PasswordAuthentication authentication; public MailClient(String user, String host) { this(user, host, false); } public MailClient(String user, String host, boolean debug) { from = user + '@' + host; authentication = new PasswordAuthentication(user, user); Properties props = new Properties(); props.put("mail.user", user); props.put("mail.host", host); props.put("mail.debug", debug ? "true" : "false"); props.put("mail.store.protocol", "pop3"); props.put("mail.transport.protocol", "smtp"); session = Session.getInstance(props, this); } public PasswordAuthentication getPasswordAuthentication() { return authentication; } public void sendMessage( String to, String subject, String content) throws MessagingException { System.out.println("SENDING message from " + from + " to " + to); System.out.println(); MimeMessage msg = new MimeMessage(session); msg.addRecipients(Message.RecipientType.TO, to); msg.setSubject(subject); msg.setText(content); Transport.send(msg); } public void checkInbox(int mode) throws MessagingException, IOException { if (mode == 0) return; boolean show = (mode & SHOW_MESSAGES) > 0; boolean clear = (mode & CLEAR_MESSAGES) > 0; String action = (show ? "Show" : "") + (show && clear ? " and " : "") + (clear ? "Clear" : ""); System.out.println(action + " INBOX for " + from); Store store = session.getStore(); store.connect(); Folder root = store.getDefaultFolder(); Folder inbox = root.getFolder("inbox"); inbox.open(Folder.READ_WRITE); Message[] msgs = inbox.getMessages(); if (msgs.length == 0 && show) { System.out.println("No messages in inbox"); } for (int i = 0; i < msgs.length; i++) { MimeMessage msg = (MimeMessage)msgs[i]; if (show) { System.out.println(" From: " + msg.getFrom()[0]); System.out.println(" Subject: " + msg.getSubject()); System.out.println(" Content: " + msg.getContent()); } if (clear) { msg.setFlag(Flags.Flag.DELETED, true); } } inbox.close(true); store.close(); System.out.println(); } }

    Read the article

  • Why my button can trigger the UI to scroll and my TimerTask inside the activity can't?

    - by Spidey
    Long Story Short: a method of my activity updates and scrolls the ListView through an ArrayAdapter like it should, but a method of an internal TimerTask for polling messages (which are displayed in the ListView) updates the ListView, but don't scroll it. Why? Long Story: I have a chat activity with this layout: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#fff" > <ListView android:id="@+id/messageList" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stackFromBottom="true" android:transcriptMode="alwaysScroll" android:layout_weight="1" android:fadeScrollbars="true" /> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" > <EditText android:id="@+id/message" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" /> <Button android:id="@+id/button_send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Send" android:onClick="sendMessage" /> </LinearLayout> </LinearLayout> The internal listView (with id messageList) is populated by an ArrayAdapter which inflates the XML below and replaces strings in it. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:clickable="false" android:background="#fff" android:paddingLeft="2dp" android:paddingRight="2dp" > <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" android:textColor="#00F" android:typeface="monospace" android:text="2010-10-12 12:12:03" android:gravity="left" /> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/sender" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="16sp" android:textColor="#f84" android:text="spidey" android:gravity="right" android:textStyle="bold" /> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/body" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="14sp" android:padding="1dp" android:gravity="left" android:layout_below="@id/date" android:text="Mensagem muito legal 123 quatro cinco seis." android:textColor="#000" /> </RelativeLayout> The problem is: in the main layout, I have a EditText for the chat message, and a Button to send the message. I have declared the adapter in the activity scope: public class ChatManager extends Activity{ private EditText et; private ListView lv; private Timestamp lastDate = null; private long campaignId; private ChatAdapter ca; private List<ChatMessage> vetMsg = new ArrayList<ChatMessage>(); private Timer chatPollingTimer; private static final int CHAT_POLLING_PERIOD = 10000; ... } So, inside sendMessage(View v), the notifyDataSetChanged() scrolls the ListView acordingly, so I can see the latest chat messages automatically: public void sendMessage(View v) { String msg = et.getText().toString(); if(msg.length() == 0){ return; } et.setText(""); String xml = ServerCom.sendAndGetChatMessages(campaignId, lastDate, msg); Vector<ChatMessage> vetNew = Chat.parse(new InputSource(new StringReader(xml))); //Pegando a última data if(!vetNew.isEmpty()){ lastDate = vetNew.lastElement().getDateSent(); //Atualizando a tela vetMsg.addAll(vetNew); ca.notifyDataSetChanged(); } } But inside my TimerTask, I can't. The ListView IS UPDATED, but it just don't scroll automatically. What am I doing wrong? private class chatPollingTask extends TimerTask { @Override public void run() { String xml; if(lastDate != null){ //Chama o Updater xml = ServerCom.getChatMessages(campaignId, lastDate); }else{ //Chama o init denovo xml = ServerCom.getChatMessages(campaignId); } Vector<ChatMessage> vetNew = Chat.parse(new InputSource(new StringReader(xml))); if(!(vetNew.isEmpty())){ //TODO: descobrir porque o chat não está rolando quando chegam novas mensagens //Descobrir também como forçar o rolamento, enquanto o bug não for corrigido. Log.d("CHAT", "New message(s) acquired!"); lastDate = vetNew.lastElement().getDateSent(); vetMsg.addAll(vetNew); ca.notifyDataSetChanged(); } } } How can I force the scroll to the bottom? I've tried using scrollTo using lv.getBottom()-lv.getHeight(), but didn't work. Is this a bug in the Android SDK? Sorry for the MASSIVE amount of code, but I guess this way the question gets pretty clear.

    Read the article

  • Android Actionbar Tabs + Fragments + Service

    - by Vladimir
    So, I have 3 problems with my code: 1) I want that each tab saves its state. So that a TextView shows changed text if it was changed. 2) if I go to Tab2 then to Tab1 I can't see the content of the fragments. Only if I touch on the already selected tab, it shows me the content 3) I can't correctly connect/bind and unbind service to Fragment Text must be changed from Service. Please help, I don't know how I realize my intent. MyActivity.java package com.example.tabs; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; public class MyActivity extends Activity { private static String ACTION_BAR_INDEX = "ACTION_BAR_INDEX"; private Tab tTab1; private Tab tTab2; private static MyService.MyBinder myBinder; private static Intent myServiceIntent; private static MyService myService; private TabListener<Tab1> tab1Listener; private TabListener<Tab2> tab2Listener; private static ServiceConnection myConnection = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder binder) { myBinder = (MyService.MyBinder) binder; myService = myBinder.getService(); myBinder.setCallbackHandler(myServiceHandler); } public void onServiceDisconnected(ComponentName name) { myService = null; myBinder = null; } }; /** Callbackhandler. */ private static Handler myServiceHandler = new Handler() { public void handleMessage(Message message) { super.handleMessage(message); Bundle bundle = message.getData(); if (bundle != null) { String text = bundle.getString("Text1", ""); if (!text.equals("")) { } } } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myServiceIntent = new Intent(this, MyService.class); bindService(myServiceIntent, myConnection, Context.BIND_AUTO_CREATE); if (!isServiceRunning()) { startService(myServiceIntent); } final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayShowTitleEnabled(false); tTab1 = actionBar.newTab(); tab1Listener = new TabListener<Tab1>(this, R.id.fl_main, Tab1.class); tTab1.setTag("Tab_1"); tTab1.setText("Tab_1"); tTab1.setTabListener(tab1Listener); tTab2 = actionBar.newTab(); tab2Listener = new TabListener<Tab2>(this, R.id.fl_main, Tab2.class); tTab2.setTag("Tab_2"); tTab2.setText("Tab_2"); tTab2.setTabListener(tab2Listener); actionBar.addTab(tTab1, 0); actionBar.addTab(tTab2, 1); } @Override public void onResume() { super.onResume(); SharedPreferences sp = getPreferences(Activity.MODE_PRIVATE); int actionBarIndex = sp.getInt(ACTION_BAR_INDEX, 0); getActionBar().setSelectedNavigationItem(actionBarIndex); } protected void onSaveInstanceState(Bundle outState) { // Save the current Action Bar tab selection int actionBarIndex = getActionBar().getSelectedTab().getPosition(); SharedPreferences.Editor editor = getPreferences(Activity.MODE_PRIVATE).edit(); editor.putInt(ACTION_BAR_INDEX, actionBarIndex); editor.apply(); // Detach each of the Fragments FragmentTransaction ft = getFragmentManager().beginTransaction(); if (tab2Listener.fragment != null) { ft.detach(tab2Listener.fragment); } if (tab1Listener.fragment != null) { ft.detach(tab1Listener.fragment); } ft.commit(); super.onSaveInstanceState(outState); } protected void onRestoreInstanceState(Bundle savedInstanceState) { // Find the recreated Fragments and assign them to their associated Tab // Listeners. tab1Listener.fragment = getFragmentManager().findFragmentByTag(Tab1.class.getName()); tab2Listener.fragment = getFragmentManager().findFragmentByTag(Tab2.class.getName()); // Restore the previous Action Bar tab selection. SharedPreferences sp = getPreferences(Activity.MODE_PRIVATE); int actionBarIndex = sp.getInt(ACTION_BAR_INDEX, 0); getActionBar().setSelectedNavigationItem(actionBarIndex); super.onRestoreInstanceState(savedInstanceState); } public boolean isServiceRunning() { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (MyService.class.getName().equals(service.service.getClassName())) { return true; } } return false; } @Override protected void onDestroy() { super.onDestroy(); unbindService(myConnection); stopService(myServiceIntent); } public static class TabListener<T extends Fragment> implements ActionBar.TabListener { private Fragment fragment; private Activity activity; private Class<T> fragmentClass; private int fragmentContainer; public TabListener(Activity activity, int fragmentContainer, Class<T> fragmentClass) { this.activity = activity; this.fragmentContainer = fragmentContainer; this.fragmentClass = fragmentClass; } public void onTabReselected(Tab tab, FragmentTransaction ft) { if (fragment != null) { ft.attach(fragment); } } public void onTabSelected(Tab tab, FragmentTransaction ft) { if (fragment == null) { String fragmentName = fragmentClass.getName(); fragment = Fragment.instantiate(activity, fragmentName); ft.add(fragmentContainer, fragment, fragmentName); } else { ft.detach(fragment); } } public void onTabUnselected(Tab tab, FragmentTransaction ft) { if (fragment != null) { ft.detach(fragment); } } } } MyService.java package com.example.tabs; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; public class MyService extends Service { private final IBinder myBinder = new MyBinder(); private static Handler myServiceHandler; public IBinder onBind(Intent intent) { return myBinder; } public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); return START_STICKY; } public void sendMessage(String sText, int id) { Bundle bundle = new Bundle(); bundle.putString("Text" + id, sText); Message bundleMessage = new Message(); bundleMessage.setData(bundle); myServiceHandler.sendMessage(bundleMessage); } public class MyBinder extends Binder { public MyService getService() { return MyService.this; } public void setCallbackHandler(Handler myActivityHandler) { myServiceHandler = myActivityHandler; } public void removeCallbackHandler() { myServiceHandler = null; } } } Tab1.java package com.example.tabs; import android.app.Activity; import android.app.Fragment; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Tab1 extends Fragment { public static String TAG = Tab1.class.getClass().getSimpleName(); private static TextView tvText; private EditText editText; private static MyService.MyBinder myBinder; private static Intent myServiceIntent; private static MyService myService; private static ServiceConnection myConnection = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder binder) { myBinder = (MyService.MyBinder) binder; myService = myBinder.getService(); myBinder.setCallbackHandler(myServiceHandler); } public void onServiceDisconnected(ComponentName name) { myService = null; myBinder = null; } }; /** Callbackhandler. */ private static Handler myServiceHandler = new Handler() { public void handleMessage(Message message) { super.handleMessage(message); Bundle bundle = message.getData(); if (bundle != null) { String text = bundle.getString("Text1", ""); if (!text.equals("")) { tvText.setText(text); } } } }; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tab1, container, false); tvText = (TextView) view.findViewById(R.id.tv_tab1); editText = (EditText) view.findViewById(R.id.editText1); Button btn1 = (Button) view.findViewById(R.id.btn_change_text_1); btn1.setOnClickListener(new OnClickListener() { public void onClick(View v) { myService.sendMessage(String.valueOf(editText.getText()), 1); } }); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); myServiceIntent = new Intent(activity, MyService.class); activity.bindService(myServiceIntent, myConnection, Context.BIND_AUTO_CREATE); } @Override public void onDetach() { super.onDetach(); getActivity().unbindService(myConnection); } } Tab2.java package com.example.tabs; import android.app.Activity; import android.app.Fragment; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Tab2 extends Fragment { public static String TAG = Tab2.class.getClass().getSimpleName(); private static TextView tvText; private EditText editText; private static MyService.MyBinder myBinder; private static Intent myServiceIntent; private static MyService myService; private static ServiceConnection myConnection = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder binder) { myBinder = (MyService.MyBinder) binder; myService = myBinder.getService(); myBinder.setCallbackHandler(myServiceHandler); } public void onServiceDisconnected(ComponentName name) { myService = null; myBinder = null; } }; /** Callbackhandler. */ private static Handler myServiceHandler = new Handler() { public void handleMessage(Message message) { super.handleMessage(message); Bundle bundle = message.getData(); if (bundle != null) { String text = bundle.getString("Text1", ""); if (!text.equals("")) { tvText.setText(text); } } } }; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.tab2, container, false); tvText = (TextView) view.findViewById(R.id.tv_tab2); editText = (EditText) view.findViewById(R.id.editText2); Button btn2 = (Button) view.findViewById(R.id.btn_change_text_2); btn2.setOnClickListener(new OnClickListener() { public void onClick(View v) { myService.sendMessage(String.valueOf(editText.getText()), 2); } }); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); myServiceIntent = new Intent(activity, MyService.class); activity.bindService(myServiceIntent, myConnection, Context.BIND_AUTO_CREATE); } @Override public void onDetach() { super.onDetach(); getActivity().unbindService(myConnection); } } main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/black" android:orientation="vertical" > </LinearLayout> tab1.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" > <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:ems="10" android:inputType="text" > <requestFocus /> </EditText> <Button android:id="@+id/btn_change_text_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:text="Change text" /> <TextView android:id="@+id/tv_tab1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TAB1\nTAB1\nTAB1" /> </LinearLayout> tab2.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" > <EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:ems="10" android:inputType="text" > <requestFocus /> </EditText> <Button android:id="@+id/btn_change_text_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:text="Change text" /> <TextView android:id="@+id/tv_tab2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:text="TAB2\nTAB2\nTAB2" /> </LinearLayout> AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.tabs" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="TabsPlusService" android:theme="@android:style/Theme.Holo" > <activity android:name="com.example.tabs.MyActivity" android:configChanges="orientation|keyboardHidden|screenSize" android:label="TabsPlusService" android:theme="@android:style/Theme.Holo" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".MyService" android:enabled="true" > </service> </application> </manifest>

    Read the article

  • How can I obtain a HBITMAP or HICON from a Direct2D bitmap?

    - by Tom
    Is there any way to obtain a HBITMAP or HICON from a ID2D1Bitmap * using Direct2D? I am using this function to load the bitmap. The reason I ask is because I am creating my level editor tool and would like to draw a PNG image on a standard button control. I know that you can do this using GDI+: HBITMAP hBitmap; Gdiplus::Bitmap b(L"a.png"); b.GetHBITMAP(NULL, &hBitmap); SendMessage(GetDlgItem(hDlg, IDC_BUTTON1), BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap); Is there any equivalent, simple solution using Direct2D? If possible, I would like to render multiple PNG files (some with transparency) on a single button.

    Read the article

  • Is dynamic casting Entities A good design?

    - by Milo
    For my game, Everything inherits from Entity, then other things like Player, PhysicsObject, etc, inherit from Entity. The physics engine sends collision callbacks which has an Entity* to the B that A collided on. Then, lets say A is a Bullet, A tries to cast the entity as a player, if it succeeds, it reduces the player's health. Is this a good design? The problem I have with a message system is that I'd need messages for everything, like: entity.sendMessage(SET_PLAYER_HEALTH,16); So that's why I think casting is cleaner.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9  | Next Page >